diff --git a/Cargo.lock b/Cargo.lock index 97bd1e9..e70b4fa 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2077,6 +2077,18 @@ dependencies = [ "zeroize", ] +[[package]] +name = "rustls-native-certs" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dab5152771c58876a2146916e53e35057e1a4dfa2b9df0f0305b07f611fdea4d" +dependencies = [ + "openssl-probe", + "rustls-pki-types", + "schannel", + "security-framework", +] + [[package]] name = "rustls-pemfile" version = "1.0.4" @@ -2679,12 +2691,16 @@ dependencies = [ "mail-parser 0.11.9", "mail-send", "rand", + "rustls 0.23.45", + "rustls-native-certs", "serde", "serde_json", "sha2", + "smtp-proto", "sqlx", "thiserror 2.0.20", "tokio", + "tokio-rustls 0.26.5", "tokio-test", "tower", "tower-http", diff --git a/Cargo.toml b/Cargo.toml index da93ec5..9f60d60 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -16,6 +16,13 @@ async-imap = { version = "0.11", default-features = false, features = ["runtime- async-native-tls = { version = "0.6", default-features = false, features = ["runtime-tokio"] } mail-parser = "0.11" mail-send = "0.4" +# mail-send trusts only its compiled-in webpki-roots; these let SMTP use the +# OS trust store instead, matching IMAP (native-tls) so a mail server with an +# internal-CA certificate works for both. default-features = false matters: +# rustls' defaults pull in aws-lc-rs, which needs cmake/clang to build. +rustls = { version = "0.23", default-features = false, features = ["ring", "std", "tls12"] } +tokio-rustls = { version = "0.26", default-features = false } +rustls-native-certs = "0.8" serde = { version = "1", features = ["derive"] } serde_json = "1" @@ -39,3 +46,5 @@ futures = "0.3" [dev-dependencies] tokio-test = "0.4" +# Same version mail-send uses, so tests can construct its reply type. +smtp-proto = "0.1" diff --git a/README.md b/README.md index 687ce76..83e282f 100644 --- a/README.md +++ b/README.md @@ -2,20 +2,33 @@ The sync server for [Tern](../) — the only component that ever speaks IMAP/SMTP. See [`docs/server-architecture-spec.md`](docs/server-architecture-spec.md) for the full design. -## What's built (build-order phases 1–2) +## What's built (build-order phases 1–4) - **DB schema** (`migrations/`): users/sessions, accounts + per-account sync state, messages/bodies/attachments, folders, tags, rules, devices — the full data model from the spec, even though rules/tags/threading execution isn't implemented yet. - **IMAP sync engine** (`src/imap_sync/`): one task per account — connects over TLS, selects INBOX, tracks `UIDVALIDITY` (re-syncing the account from scratch if it changes), fetches new mail headers-first (`ENVELOPE`/`FLAGS`) then lazily fills in bodies/attachments in a trailing pass, and IDLEs for pushed changes with a periodic renewal and jittered-backoff reconnect on any failure. - **Minimal REST API** (`src/api/`): local username/password auth (Argon2 + bearer session tokens), account management (IMAP credentials encrypted at rest with ChaCha20-Poly1305), folder listing, cursor-paginated message listing, single-message + thread-by-id fetch, and a polling `/events` delta endpoint. - **Thread-grouped listing** (`GET /api/threads`): one row per conversation, which is how both clients render the inbox. Grouped server-side because a thread's messages are spread through the flat list by date, so a client grouping page-by-page would split threads across page boundaries and miscount unread. +- **Sending** (`src/smtp/`, `/api/outbox`): drafts and a send queue, drained by a background worker — never in the request path (§3.3). Retries with backoff (1, 2, 4, 8, 16 min), fails fast on 5xx replies and auth or TLS errors, and reclaims messages a crashed worker left mid-send. Replies get In-Reply-To/References derived server-side from the parent message. Sent mail is filed into its thread alongside received mail. +- **Mark read** (`POST /api/threads/:id/read`) — local state only; see below. + +## How sending behaves + +A few consequences worth knowing, because they aren't visible from the UI: + +- **Sent mail exists only in Tern.** Nothing is appended to the IMAP server's Sent folder — sync is one-way (§2.1) and never writes back. If you ever use another client against the same account, it won't see mail sent from Tern. The same goes for mark-read: it's Tern-local. Bringing either to the source server is the two-way-sync item in §11, not a small add-on. +- **TLS always, enforced by type.** `mail-send`'s `connect()` returns a TLS-typed client and fails with `MissingStartTls` rather than downgrading; plaintext would need a separate `connect_plain()` which isn't used. Verified live: pointing an account at a server that doesn't offer STARTTLS fails permanently and delivers nothing. +- **SMTP trusts the OS certificate store**, same as IMAP. `mail-send` on its own trusts only compiled-in public CAs, so a mail server with an internal-CA certificate would sync fine and then fail every send. If your mail server uses an internal CA, add it to the container's trust store (`/usr/local/share/ca-certificates` + `update-ca-certificates`) and both protocols will trust it. +- **Bcc goes in the envelope only.** `mail-builder`'s `.bcc()` writes an ordinary `Bcc:` header that every recipient would see, so it's deliberately not used; a test checks that blind-copied addresses never reach the rendered message. The Bcc list is kept on the outbox row, not on the sent message. +- **Delivery is at-least-once.** If the server accepts a message but the process dies before recording it, it's re-sent. Every attempt reuses the same Message-ID, so a duplicate is at least recognisable as the same message. Exactly-once isn't achievable over SMTP. +- **SMTP port conventions:** STARTTLS by default, implicit TLS when the port is 465 — overridable per account with `smtp_use_starttls`. IMAP is implicit TLS only (993); STARTTLS on 143 isn't supported. ## What's explicitly deferred -Per the spec's suggested build order (§9), not yet built: SMTP sending/outbox, tag & rule *execution* (schema exists, engine doesn't), the JWZ threading algorithm (each message currently gets its own `thread_id` — no linking/merging pass yet), spam header rules, WebSocket push (the `/events` poll endpoint is the interim/fallback path), and the Android/webapp-facing UnifiedPush integration. +Per the spec's suggested build order (§9), not yet built: tag & rule *execution* (schema exists, engine doesn't), the JWZ threading algorithm (each message currently gets its own `thread_id` — no linking/merging pass yet), spam header rules, WebSocket push (the `/events` poll endpoint is the interim/fallback path), and the Android/webapp-facing UnifiedPush integration. Also deferred, and worth knowing because they aren't obvious from the code: -- **Mutation endpoints.** There's no way to mark read, tag, or move a message yet. These arrive with phases 4–5, when there's something to mutate. +- **Most mutations.** Mark-read exists; tagging and moving to folders arrive with phase 5. - **Permissive CORS.** `CorsLayer::permissive()` is a dev convenience so the Vite dev server on another port can talk to the API. Tighten it when the webapp is served from the same origin behind nginx. - **API-level rate limiting.** The nginx layer covers most of this — see [`nginx-rate-limiting.md`](nginx-rate-limiting.md). A per-username limiter in the API is the remaining gap. diff --git a/migrations/0005_outbox.sql b/migrations/0005_outbox.sql new file mode 100644 index 0000000..1a00ed4 --- /dev/null +++ b/migrations/0005_outbox.sql @@ -0,0 +1,51 @@ +-- Sending: SMTP submission via an outbox queue (server-architecture-spec.md §3.3). + +-- An IMAP username isn't necessarily an email address ("alice" vs +-- "alice@example.com"), so the sender identity is stored explicitly. +ALTER TABLE accounts ADD COLUMN email_address TEXT; +ALTER TABLE accounts ADD COLUMN display_name TEXT; +UPDATE accounts SET email_address = username WHERE username LIKE '%@%'; + +-- Sent mail lives alongside synced mail so a thread shows both sides of the +-- conversation. Sync is one-way and only reads INBOX, so without this a +-- reply would vanish from its own thread. Sent rows have no IMAP UID. +ALTER TABLE messages ADD COLUMN source TEXT NOT NULL DEFAULT 'imap'; +ALTER TABLE messages ALTER COLUMN uid DROP NOT NULL; +ALTER TABLE messages ADD CONSTRAINT messages_uid_matches_source + CHECK ((source = 'imap') = (uid IS NOT NULL)); + +CREATE TABLE outbox ( + id UUID PRIMARY KEY DEFAULT gen_random_uuid(), + user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE, + account_id UUID NOT NULL REFERENCES accounts(id) ON DELETE CASCADE, + -- draft: editable, never sent automatically + -- pending: queued, waiting for next_attempt_at + -- sending: claimed by the worker + -- sent / failed: terminal (failed can be edited and re-queued) + status TEXT NOT NULL DEFAULT 'draft' + CHECK (status IN ('draft', 'pending', 'sending', 'sent', 'failed')), + to_addrs TEXT[] NOT NULL DEFAULT '{}', + cc_addrs TEXT[] NOT NULL DEFAULT '{}', + bcc_addrs TEXT[] NOT NULL DEFAULT '{}', + subject TEXT NOT NULL DEFAULT '', + text_body TEXT NOT NULL DEFAULT '', + -- Reply context, derived server-side from the parent message rather than + -- trusted from the client. + in_reply_to TEXT, + references_ TEXT[] NOT NULL DEFAULT '{}', + thread_id UUID, + -- Assigned when first queued and reused on every retry, so if a server + -- accepted a message but the ack was lost, the retry is recognisably the + -- same message to recipients' clients rather than a new one. + message_id TEXT, + attempts INTEGER NOT NULL DEFAULT 0, + last_error TEXT, + next_attempt_at TIMESTAMPTZ, + sent_message_id UUID REFERENCES messages(id) ON DELETE SET NULL, + created_at TIMESTAMPTZ NOT NULL DEFAULT now(), + updated_at TIMESTAMPTZ NOT NULL DEFAULT now(), + sent_at TIMESTAMPTZ +); + +CREATE INDEX outbox_due_idx ON outbox (next_attempt_at) WHERE status = 'pending'; +CREATE INDEX outbox_user_status_idx ON outbox (user_id, status); diff --git a/src/api/accounts.rs b/src/api/accounts.rs index a0799fa..23c7d84 100644 --- a/src/api/accounts.rs +++ b/src/api/accounts.rs @@ -15,6 +15,14 @@ pub struct CreateAccountRequest { pub smtp_port: i32, pub username: String, pub password: String, + /// From address for sending. Defaults to `username` when that is + /// itself an address. + pub email_address: Option, + pub display_name: Option, + /// STARTTLS on a plain connection (587) vs TLS from the first byte + /// (465). Defaults by port, since that's the convention nearly every + /// provider follows. Either way it's TLS — there's no plaintext option. + pub smtp_use_starttls: Option, } pub async fn list( @@ -41,8 +49,10 @@ pub async fn create( let account: Account = sqlx::query_as( "INSERT INTO accounts \ - (user_id, name, imap_host, imap_port, smtp_host, smtp_port, username, encrypted_password, password_nonce) \ - VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9) RETURNING *", + (user_id, name, imap_host, imap_port, smtp_host, smtp_port, username, encrypted_password, \ + password_nonce, email_address, display_name, smtp_use_starttls) \ + VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, \ + COALESCE($10, CASE WHEN $7 LIKE '%@%' THEN $7 END), $11, $12) RETURNING *", ) .bind(user.user_id) .bind(&req.name) @@ -53,6 +63,9 @@ pub async fn create( .bind(&req.username) .bind(&encrypted.ciphertext) .bind(&encrypted.nonce) + .bind(req.email_address.as_deref().map(str::trim).filter(|e| !e.is_empty())) + .bind(req.display_name.as_deref().map(str::trim).filter(|n| !n.is_empty())) + .bind(req.smtp_use_starttls.unwrap_or(req.smtp_port != 465)) .fetch_one(&state.pool) .await?; diff --git a/src/api/mod.rs b/src/api/mod.rs index 4aa0d33..7d44afc 100644 --- a/src/api/mod.rs +++ b/src/api/mod.rs @@ -4,6 +4,7 @@ pub mod events; pub mod folders; pub mod messages; pub mod middleware; +pub mod outbox; pub mod router; pub mod state; pub mod threads; diff --git a/src/api/outbox.rs b/src/api/outbox.rs new file mode 100644 index 0000000..d61d6ed --- /dev/null +++ b/src/api/outbox.rs @@ -0,0 +1,267 @@ +//! Drafts and the send queue (server-architecture-spec.md §3.3). +//! +//! A draft and a queued message are the same row in different states, so +//! "save as draft" and "send" are one endpoint with a flag, and sending an +//! existing draft is a state transition rather than a copy. +//! +//! Nothing here talks SMTP — queuing just marks a row pending and wakes the +//! worker, so a slow or unreachable mail server never blocks a request. + +use crate::api::middleware::CurrentUser; +use crate::api::state::AppState; +use crate::error::{ApiError, ApiResult}; +use crate::models::account::Account; +use crate::models::outbox::OutboxItem; +use crate::models::Message; +use crate::smtp::compose; +use axum::{ + extract::{Path, State}, + Json, +}; +use serde::Deserialize; +use uuid::Uuid; + +#[derive(Deserialize)] +pub struct ComposeRequest { + pub account_id: Option, + #[serde(default)] + pub to: Vec, + #[serde(default)] + pub cc: Vec, + #[serde(default)] + pub bcc: Vec, + #[serde(default)] + pub subject: String, + #[serde(default)] + pub text_body: String, + /// Tern's id for the message being replied to. Threading headers are + /// derived from it server-side rather than accepted from the client. + pub reply_to_message_id: Option, + /// false = save as draft, true = queue for sending. + #[serde(default)] + pub send: bool, +} + +#[derive(Deserialize)] +pub struct UpdateDraftRequest { + pub to: Vec, + pub cc: Vec, + pub bcc: Vec, + pub subject: String, + pub text_body: String, +} + +/// Everything the reader can still act on. Sent items are left out: once +/// sent, a message lives in its thread like any other. +pub async fn list( + State(state): State, + user: CurrentUser, +) -> ApiResult>> { + let items: Vec = sqlx::query_as( + "SELECT * FROM outbox WHERE user_id = $1 AND status <> 'sent' ORDER BY updated_at DESC", + ) + .bind(user.user_id) + .fetch_all(&state.pool) + .await?; + Ok(Json(items)) +} + +pub async fn create( + State(state): State, + user: CurrentUser, + Json(req): Json, +) -> ApiResult> { + let to = compose::normalize_recipients(&req.to).map_err(ApiError::BadRequest)?; + let cc = compose::normalize_recipients(&req.cc).map_err(ApiError::BadRequest)?; + let bcc = compose::normalize_recipients(&req.bcc).map_err(ApiError::BadRequest)?; + + let parent = match req.reply_to_message_id { + Some(id) => Some(load_owned_message(&state, user.user_id, id).await?), + None => None, + }; + + // A reply goes out from the account that received the original, unless + // the reader explicitly picked another one. + let account_id = req + .account_id + .or(parent.as_ref().map(|p| p.account_id)) + .ok_or_else(|| ApiError::BadRequest("account_id is required".into()))?; + let account = load_owned_account(&state, user.user_id, account_id).await?; + + // Checked before inserting, so a rejected send doesn't leave an orphan + // draft behind for a retrying client to duplicate. + if req.send { + check_sendable(&account, &to, &cc, &bcc)?; + } + + let (in_reply_to, references) = match &parent { + Some(p) => compose::reply_headers(p.message_id.as_deref(), &p.references_), + None => (None, Vec::new()), + }; + + let item: OutboxItem = sqlx::query_as( + "INSERT INTO outbox \ + (user_id, account_id, to_addrs, cc_addrs, bcc_addrs, subject, text_body, \ + in_reply_to, references_, thread_id) \ + VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10) RETURNING *", + ) + .bind(user.user_id) + .bind(account.id) + .bind(&to) + .bind(&cc) + .bind(&bcc) + .bind(&req.subject) + .bind(&req.text_body) + .bind(&in_reply_to) + .bind(&references) + .bind(parent.as_ref().map(|p| p.thread_id)) + .fetch_one(&state.pool) + .await?; + + if req.send { + return queue(&state, &account, item).await.map(Json); + } + Ok(Json(item)) +} + +/// Editing a failed message turns it back into a draft: once changed it's +/// no longer the thing that failed, and it shouldn't be retried as-is. +pub async fn update( + State(state): State, + user: CurrentUser, + Path(id): Path, + Json(req): Json, +) -> ApiResult> { + let to = compose::normalize_recipients(&req.to).map_err(ApiError::BadRequest)?; + let cc = compose::normalize_recipients(&req.cc).map_err(ApiError::BadRequest)?; + let bcc = compose::normalize_recipients(&req.bcc).map_err(ApiError::BadRequest)?; + + let item: Option = sqlx::query_as( + "UPDATE outbox SET to_addrs = $3, cc_addrs = $4, bcc_addrs = $5, subject = $6, \ + text_body = $7, status = 'draft', last_error = NULL, updated_at = now() \ + WHERE id = $1 AND user_id = $2 AND status IN ('draft', 'failed') \ + RETURNING *", + ) + .bind(id) + .bind(user.user_id) + .bind(&to) + .bind(&cc) + .bind(&bcc) + .bind(&req.subject) + .bind(&req.text_body) + .fetch_optional(&state.pool) + .await?; + + item.map(Json).ok_or_else(|| editable_or_not_found(id)) +} + +pub async fn send( + State(state): State, + user: CurrentUser, + Path(id): Path, +) -> ApiResult> { + let item: OutboxItem = sqlx::query_as( + "SELECT * FROM outbox WHERE id = $1 AND user_id = $2 AND status IN ('draft', 'failed')", + ) + .bind(id) + .bind(user.user_id) + .fetch_optional(&state.pool) + .await? + .ok_or_else(|| editable_or_not_found(id))?; + + let account = load_owned_account(&state, user.user_id, item.account_id).await?; + queue(&state, &account, item).await.map(Json) +} + +pub async fn delete( + State(state): State, + user: CurrentUser, + Path(id): Path, +) -> ApiResult> { + let deleted = sqlx::query( + "DELETE FROM outbox WHERE id = $1 AND user_id = $2 AND status IN ('draft', 'failed')", + ) + .bind(id) + .bind(user.user_id) + .execute(&state.pool) + .await? + .rows_affected(); + + if deleted == 0 { + return Err(editable_or_not_found(id)); + } + Ok(Json(serde_json::json!({ "ok": true }))) +} + +/// Validates that the message is actually sendable, assigns its Message-ID +/// (once — retries reuse it), marks it pending and wakes the worker so it +/// goes out now rather than at the next poll. +async fn queue(state: &AppState, account: &Account, item: OutboxItem) -> ApiResult { + let sender = check_sendable(account, &item.to_addrs, &item.cc_addrs, &item.bcc_addrs)?; + + let item: OutboxItem = sqlx::query_as( + "UPDATE outbox SET status = 'pending', attempts = 0, last_error = NULL, \ + message_id = COALESCE(message_id, $2), next_attempt_at = now(), updated_at = now() \ + WHERE id = $1 RETURNING *", + ) + .bind(item.id) + .bind(compose::new_message_id(&sender)) + .fetch_one(&state.pool) + .await?; + + state.outbox_wake.notify_one(); + Ok(item) +} + +fn check_sendable( + account: &Account, + to: &[String], + cc: &[String], + bcc: &[String], +) -> ApiResult { + if to.is_empty() && cc.is_empty() && bcc.is_empty() { + return Err(ApiError::BadRequest( + "at least one recipient is required".into(), + )); + } + account.sender_address().ok_or_else(|| { + ApiError::BadRequest( + "this account has no sender address — set email_address on the account first".into(), + ) + }) +} + +async fn load_owned_account( + state: &AppState, + user_id: Uuid, + account_id: Uuid, +) -> ApiResult { + sqlx::query_as("SELECT * FROM accounts WHERE id = $1 AND user_id = $2") + .bind(account_id) + .bind(user_id) + .fetch_optional(&state.pool) + .await? + .ok_or(ApiError::NotFound) +} + +async fn load_owned_message( + state: &AppState, + user_id: Uuid, + message_id: Uuid, +) -> ApiResult { + sqlx::query_as( + "SELECT m.* FROM messages m JOIN accounts a ON a.id = m.account_id \ + WHERE m.id = $1 AND a.user_id = $2", + ) + .bind(message_id) + .bind(user_id) + .fetch_optional(&state.pool) + .await? + .ok_or(ApiError::NotFound) +} + +fn editable_or_not_found(id: Uuid) -> ApiError { + ApiError::BadRequest(format!( + "outbox item {id} doesn't exist or isn't editable — only drafts and failed messages can be changed" + )) +} diff --git a/src/api/router.rs b/src/api/router.rs index 5486e34..a7a896e 100644 --- a/src/api/router.rs +++ b/src/api/router.rs @@ -1,6 +1,6 @@ use crate::api::state::AppState; -use crate::api::{accounts, auth, events, folders, messages, threads}; -use axum::routing::{delete, get, post}; +use crate::api::{accounts, auth, events, folders, messages, outbox, threads}; +use axum::routing::{delete, get, post, put}; use axum::Router; use tower_http::cors::CorsLayer; use tower_http::trace::TraceLayer; @@ -16,6 +16,13 @@ pub fn build(state: AppState) -> Router { .route("/api/messages/:id", get(messages::get)) .route("/api/threads", get(threads::list)) .route("/api/threads/:id", get(messages::get_thread)) + .route("/api/threads/:id/read", post(threads::mark_read)) + .route("/api/outbox", get(outbox::list).post(outbox::create)) + .route( + "/api/outbox/:id", + put(outbox::update).delete(outbox::delete), + ) + .route("/api/outbox/:id/send", post(outbox::send)) .route("/api/events", get(events::poll)) .route("/healthz", get(|| async { "ok" })) .layer(TraceLayer::new_for_http()) diff --git a/src/api/state.rs b/src/api/state.rs index cb49d53..fc416b9 100644 --- a/src/api/state.rs +++ b/src/api/state.rs @@ -2,6 +2,8 @@ use crate::config::Config; use crate::crypto::CredentialCipher; use crate::storage::BlobStore; use sqlx::PgPool; +use std::sync::Arc; +use tokio::sync::Notify; #[derive(Clone)] pub struct AppState { @@ -10,4 +12,7 @@ pub struct AppState { pub blobs: BlobStore, pub session_ttl_hours: i64, pub config: Config, + /// Wakes the outbox worker as soon as something is queued, so a send + /// goes out immediately rather than at the next idle poll. + pub outbox_wake: Arc, } diff --git a/src/api/threads.rs b/src/api/threads.rs index e73c205..8078753 100644 --- a/src/api/threads.rs +++ b/src/api/threads.rs @@ -92,3 +92,26 @@ pub async fn list( next_cursor, })) } + +/// Marks every message in a thread read. Local state only — sync is +/// one-way (server-architecture-spec.md §2.1), so this never reaches the +/// source IMAP server. +pub async fn mark_read( + State(state): State, + user: CurrentUser, + axum::extract::Path(thread_id): axum::extract::Path, +) -> ApiResult> { + let updated = sqlx::query( + r#"UPDATE messages m SET flags = array_append(m.flags, '\Seen') + FROM accounts a + WHERE a.id = m.account_id AND a.user_id = $1 AND m.thread_id = $2 + AND NOT ('\Seen' = ANY(m.flags))"#, + ) + .bind(user.user_id) + .bind(thread_id) + .execute(&state.pool) + .await? + .rows_affected(); + + Ok(Json(serde_json::json!({ "updated": updated }))) +} diff --git a/src/imap_sync/connection.rs b/src/imap_sync/connection.rs index 36df60f..fd446d4 100644 --- a/src/imap_sync/connection.rs +++ b/src/imap_sync/connection.rs @@ -164,12 +164,28 @@ impl AccountSyncer { .execute(&self.pool) .await?; } + // Account creation leaves uidvalidity NULL, so this is a first + // sync rather than a change — record it without the scary reset + // path, which would otherwise log a false "UIDVALIDITY changed" + // warning for every newly added account. + Some((None,)) => { + sqlx::query( + "UPDATE sync_state SET uidvalidity = $2, updated_at = now() WHERE account_id = $1", + ) + .bind(self.account.id) + .bind(server_uidvalidity) + .execute(&self.pool) + .await?; + } Some((stored,)) if stored != server_uidvalidity => { // UIDVALIDITY changed: every previously cached UID is now - // meaningless. Drop this account's messages and start over. + // meaningless. Drop this account's synced messages and start + // over — only the IMAP-sourced ones: mail sent from Tern + // shares this table but exists nowhere else, so deleting it + // here would lose it for good. tracing::warn!(account_id = %self.account.id, "UIDVALIDITY changed, re-syncing folder from scratch"); let mut tx = self.pool.begin().await?; - sqlx::query("DELETE FROM messages WHERE account_id = $1") + sqlx::query("DELETE FROM messages WHERE account_id = $1 AND source = 'imap'") .bind(self.account.id) .execute(&mut *tx) .await?; @@ -227,12 +243,14 @@ impl AccountSyncer { let subject = envelope .and_then(|e| e.subject.as_ref()) .map(|s| String::from_utf8_lossy(s).to_string()); + // ENVELOPE gives these bracketed; mail-parser (which overwrites + // them once the body arrives) gives them bare. Store one form. let message_id = envelope .and_then(|e| e.message_id.as_ref()) - .map(|s| String::from_utf8_lossy(s).to_string()); + .map(|s| crate::smtp::compose::bare_id(&String::from_utf8_lossy(s))); let in_reply_to = envelope .and_then(|e| e.in_reply_to.as_ref()) - .map(|s| String::from_utf8_lossy(s).to_string()); + .map(|s| crate::smtp::compose::bare_id(&String::from_utf8_lossy(s))); let flags: Vec = f.flags().map(|flag| flag_to_wire(&flag)).collect(); @@ -268,7 +286,8 @@ impl AccountSyncer { async fn fetch_pending_bodies(&self, session: &mut ImapSession) -> Result<()> { loop { let pending: Vec<(Uuid, i64)> = sqlx::query_as( - "SELECT id, uid FROM messages WHERE account_id = $1 AND body_fetched = false \ + "SELECT id, uid FROM messages \ + WHERE account_id = $1 AND source = 'imap' AND body_fetched = false \ ORDER BY uid ASC LIMIT $2", ) .bind(self.account.id) diff --git a/src/lib.rs b/src/lib.rs index 51d62b4..265e003 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -6,4 +6,5 @@ pub mod db; pub mod error; pub mod imap_sync; pub mod models; +pub mod smtp; pub mod storage; diff --git a/src/main.rs b/src/main.rs index 88daa75..aa8786d 100644 --- a/src/main.rs +++ b/src/main.rs @@ -25,12 +25,21 @@ async fn main() -> anyhow::Result<()> { // (server-architecture-spec.md §3.1) — it runs alongside the API server. tokio::spawn(imap_sync::run(pool.clone(), cipher.clone(), blobs.clone())); + let outbox_wake = std::sync::Arc::new(tokio::sync::Notify::new()); + tokio::spawn(tern_server::smtp::worker::run( + pool.clone(), + cipher.clone(), + blobs.clone(), + outbox_wake.clone(), + )); + let state = AppState { pool, cipher, blobs, session_ttl_hours: config.session_ttl_hours, config: config.clone(), + outbox_wake, }; let app = api::build(state); diff --git a/src/models/account.rs b/src/models/account.rs index d42bb03..8732de2 100644 --- a/src/models/account.rs +++ b/src/models/account.rs @@ -18,6 +18,20 @@ pub struct Account { pub encrypted_password: Vec, pub password_nonce: Vec, pub created_at: DateTime, + pub email_address: Option, + pub display_name: Option, +} + +impl Account { + /// The From address for mail sent from this account. Falls back to the + /// login name only when that is itself an address — an IMAP username is + /// often a bare "alice", which can't be sent from. + pub fn sender_address(&self) -> Option { + self.email_address + .clone() + .filter(|a| !a.trim().is_empty()) + .or_else(|| self.username.contains('@').then(|| self.username.clone())) + } } /// What the API actually returns — never the encrypted credential blob. @@ -31,6 +45,8 @@ pub struct AccountPublic { pub smtp_host: String, pub smtp_port: i32, pub username: String, + pub email_address: Option, + pub display_name: Option, pub created_at: DateTime, } @@ -45,6 +61,8 @@ impl From for AccountPublic { smtp_host: a.smtp_host, smtp_port: a.smtp_port, username: a.username, + email_address: a.email_address, + display_name: a.display_name, created_at: a.created_at, } } diff --git a/src/models/message.rs b/src/models/message.rs index f629a9e..c6743f2 100644 --- a/src/models/message.rs +++ b/src/models/message.rs @@ -7,7 +7,8 @@ pub struct Message { pub id: Uuid, pub account_id: Uuid, pub folder_id: Option, - pub uid: i64, + /// None for mail sent from Tern, which never came from IMAP. + pub uid: Option, pub message_id: Option, pub in_reply_to: Option, pub references_: Vec, @@ -22,6 +23,8 @@ pub struct Message { pub spam_score: Option, pub body_fetched: bool, pub raw_blob_ref: Option, + /// 'imap' for synced mail, 'sent' for mail sent from Tern. + pub source: String, pub created_at: DateTime, } diff --git a/src/models/mod.rs b/src/models/mod.rs index 03c2595..ad06b5a 100644 --- a/src/models/mod.rs +++ b/src/models/mod.rs @@ -1,6 +1,7 @@ pub mod account; pub mod folder; pub mod message; +pub mod outbox; pub mod user; pub use account::Account; diff --git a/src/models/outbox.rs b/src/models/outbox.rs new file mode 100644 index 0000000..4d7e83f --- /dev/null +++ b/src/models/outbox.rs @@ -0,0 +1,27 @@ +use chrono::{DateTime, Utc}; +use serde::Serialize; +use uuid::Uuid; + +#[derive(Debug, Clone, sqlx::FromRow, Serialize)] +pub struct OutboxItem { + pub id: Uuid, + pub user_id: Uuid, + pub account_id: Uuid, + pub status: String, + pub to_addrs: Vec, + pub cc_addrs: Vec, + pub bcc_addrs: Vec, + pub subject: String, + pub text_body: String, + pub in_reply_to: Option, + pub references_: Vec, + pub thread_id: Option, + pub message_id: Option, + pub attempts: i32, + pub last_error: Option, + pub next_attempt_at: Option>, + pub sent_message_id: Option, + pub created_at: DateTime, + pub updated_at: DateTime, + pub sent_at: Option>, +} diff --git a/src/smtp/compose.rs b/src/smtp/compose.rs new file mode 100644 index 0000000..4aa72a0 --- /dev/null +++ b/src/smtp/compose.rs @@ -0,0 +1,316 @@ +//! Turning an outbox row into bytes on the wire plus an SMTP envelope. +//! +//! Kept free of I/O so the parts that must be exactly right — what ends up +//! in headers versus the envelope, and how reply headers chain — are unit +//! tested without a mail server. + +use mail_send::mail_builder::MessageBuilder; +use uuid::Uuid; + +/// Who the SMTP transaction is addressed to. Distinct from the headers: +/// Bcc recipients appear here and nowhere in the message itself. +#[derive(Debug, Clone, PartialEq)] +pub struct Envelope { + pub mail_from: String, + pub rcpt_to: Vec, +} + +pub struct Sender<'a> { + pub email: &'a str, + pub display_name: Option<&'a str>, +} + +pub struct Draft<'a> { + pub to: &'a [String], + pub cc: &'a [String], + pub bcc: &'a [String], + pub subject: &'a str, + pub text_body: &'a str, + pub message_id: &'a str, + pub in_reply_to: Option<&'a str>, + pub references: &'a [String], + pub date_unix: i64, +} + +/// Message-IDs are stored without angle brackets. IMAP's ENVELOPE returns +/// them bracketed while mail-parser returns them bare, so everything is +/// normalised to one form at the boundary — otherwise the same message +/// could be stored under two different IDs depending on which path wrote it +/// last, and reply chains / threading would fail to match. +pub fn bare_id(id: &str) -> String { + id.trim() + .trim_start_matches('<') + .trim_end_matches('>') + .trim() + .to_string() +} + +/// Validates and normalises a recipient list from user input: trims, +/// drops blanks, dedupes case-insensitively. Rejects anything that isn't a +/// plain `local@domain` — in particular anything with whitespace, commas, +/// angle brackets or line breaks, which are the ingredients for header +/// injection or smuggling extra recipients into a field. +pub fn normalize_recipients(input: &[String]) -> Result, String> { + let mut out: Vec = Vec::new(); + for raw in input { + let addr = raw.trim(); + if addr.is_empty() { + continue; + } + let valid = !addr + .chars() + .any(|c| c.is_whitespace() || matches!(c, ',' | ';' | '<' | '>' | '"')) + && matches!(addr.split_once('@'), Some((local, domain)) + if !local.is_empty() && !domain.is_empty() && !domain.contains('@') && domain.contains('.')); + if !valid { + return Err(format!("not a valid email address: {addr:?}")); + } + if !out.iter().any(|a| a.eq_ignore_ascii_case(addr)) { + out.push(addr.to_string()); + } + } + Ok(out) +} + +/// Headers for a reply to `parent`: In-Reply-To is the parent's ID, and +/// References is the parent's chain plus the parent itself. +/// +/// Long chains are trimmed to the first ID plus the most recent ones, as +/// RFC 5322 §3.6.4 suggests — the root anchors the thread, the tail links +/// the immediate ancestors, and the middle is what's safe to drop. +pub fn reply_headers( + parent_message_id: Option<&str>, + parent_references: &[String], +) -> (Option, Vec) { + const MAX_REFERENCES: usize = 20; + + let parent = parent_message_id.map(bare_id).filter(|id| !id.is_empty()); + + let mut refs: Vec = Vec::new(); + for id in parent_references + .iter() + .map(|r| bare_id(r)) + .chain(parent.clone()) + { + if !id.is_empty() && !refs.contains(&id) { + refs.push(id); + } + } + + if refs.len() > MAX_REFERENCES { + let tail = refs.split_off(refs.len() - (MAX_REFERENCES - 1)); + refs.truncate(1); + refs.extend(tail); + } + + (parent, refs) +} + +pub fn new_message_id(sender_email: &str) -> String { + let domain = sender_email + .rsplit_once('@') + .map(|(_, d)| d) + .unwrap_or("tern.invalid"); + format!("{}@{}", Uuid::new_v4(), domain) +} + +pub fn render(sender: &Sender, draft: &Draft) -> anyhow::Result<(Vec, Envelope)> { + let from: (String, String) = ( + sender.display_name.unwrap_or("").to_string(), + sender.email.to_string(), + ); + + let mut builder = MessageBuilder::new() + .from(from) + .subject(strip_line_breaks(draft.subject)) + .message_id(bare_id(draft.message_id)) + .date(draft.date_unix) + .text_body(draft.text_body.to_string()); + + if !draft.to.is_empty() { + builder = builder.to(draft.to.to_vec()); + } + if !draft.cc.is_empty() { + builder = builder.cc(draft.cc.to_vec()); + } + // Deliberately no builder.bcc(): mail-builder writes Bcc as an ordinary + // header, which would show every blind-copied address to every + // recipient. Bcc goes into the envelope below and nowhere else. + if let Some(parent) = draft.in_reply_to { + builder = builder.in_reply_to(bare_id(parent)); + } + if !draft.references.is_empty() { + builder = builder.references( + draft + .references + .iter() + .map(|r| bare_id(r)) + .collect::>(), + ); + } + + let bytes = builder.write_to_vec()?; + + let mut rcpt_to: Vec = Vec::new(); + for addr in draft.to.iter().chain(draft.cc).chain(draft.bcc) { + if !rcpt_to.iter().any(|a| a.eq_ignore_ascii_case(addr)) { + rcpt_to.push(addr.clone()); + } + } + + Ok(( + bytes, + Envelope { + mail_from: sender.email.to_string(), + rcpt_to, + }, + )) +} + +fn strip_line_breaks(s: &str) -> String { + s.replace(['\r', '\n'], " ") +} + +#[cfg(test)] +mod tests { + use super::*; + + fn draft<'a>(to: &'a [String], cc: &'a [String], bcc: &'a [String]) -> Draft<'a> { + Draft { + to, + cc, + bcc, + subject: "Hello", + text_body: "body text", + message_id: "abc@example.com", + in_reply_to: None, + references: &[], + date_unix: 1_790_000_000, + } + } + + fn sender() -> Sender<'static> { + Sender { + email: "alice@example.com", + display_name: Some("Alice"), + } + } + + #[test] + fn bcc_goes_in_envelope_but_never_in_the_message() { + let to = vec!["bob@example.com".to_string()]; + let bcc = vec!["secret@example.com".to_string()]; + let (bytes, envelope) = render(&sender(), &draft(&to, &[], &bcc)).unwrap(); + let text = String::from_utf8_lossy(&bytes); + + assert!(envelope.rcpt_to.contains(&"secret@example.com".to_string())); + assert!( + !text.contains("secret@example.com"), + "bcc address leaked into message:\n{text}" + ); + assert!( + !text.to_ascii_lowercase().contains("bcc:"), + "a Bcc header was written:\n{text}" + ); + } + + #[test] + fn envelope_dedupes_across_fields() { + let to = vec!["bob@example.com".to_string()]; + let cc = vec![ + "BOB@example.com".to_string(), + "carol@example.com".to_string(), + ]; + let (_, envelope) = render(&sender(), &draft(&to, &cc, &[])).unwrap(); + assert_eq!( + envelope.rcpt_to, + vec!["bob@example.com", "carol@example.com"] + ); + assert_eq!(envelope.mail_from, "alice@example.com"); + } + + #[test] + fn reply_headers_are_rendered_bracketed() { + let to = vec!["bob@example.com".to_string()]; + let refs = vec![ + "root@example.com".to_string(), + "parent@example.com".to_string(), + ]; + let mut d = draft(&to, &[], &[]); + d.in_reply_to = Some("parent@example.com"); + d.references = &refs; + let text = String::from_utf8(render(&sender(), &d).unwrap().0).unwrap(); + + assert!(text.contains("In-Reply-To: "), "{text}"); + assert!( + text.contains("") && text.contains("References:"), + "{text}" + ); + assert!(text.contains("Message-ID: "), "{text}"); + } + + #[test] + fn subject_line_breaks_cannot_inject_headers() { + let to = vec!["bob@example.com".to_string()]; + let mut d = draft(&to, &[], &[]); + d.subject = "hi\r\nBcc: attacker@example.com"; + let text = String::from_utf8(render(&sender(), &d).unwrap().0).unwrap(); + assert!(!text.contains("\r\nBcc:"), "{text}"); + } + + #[test] + fn bare_id_strips_brackets_and_whitespace() { + assert_eq!(bare_id(" "), "abc@x.y"); + assert_eq!(bare_id("abc@x.y"), "abc@x.y"); + } + + #[test] + fn reply_headers_chain_parent_onto_references() { + let refs = vec!["".to_string()]; + let (irt, chain) = reply_headers(Some(""), &refs); + assert_eq!(irt.as_deref(), Some("parent@x")); + assert_eq!(chain, vec!["root@x", "parent@x"]); + } + + #[test] + fn reply_headers_trim_long_chains_keeping_root_and_tail() { + let refs: Vec = (0..30).map(|i| format!("m{i}@x")).collect(); + let (_, chain) = reply_headers(Some("parent@x"), &refs); + assert_eq!(chain.len(), 20); + assert_eq!(chain.first().unwrap(), "m0@x", "root must survive trimming"); + assert_eq!( + chain.last().unwrap(), + "parent@x", + "direct parent must survive trimming" + ); + } + + #[test] + fn recipients_are_validated_and_deduped() { + let ok = normalize_recipients(&[ + " bob@example.com ".into(), + "".into(), + "Bob@Example.com".into(), + "carol@example.org".into(), + ]) + .unwrap(); + assert_eq!(ok, vec!["bob@example.com", "carol@example.org"]); + } + + #[test] + fn recipients_reject_injection_shapes() { + for bad in [ + "bob@example.com, eve@example.com", + "Bob ", + "bob@example.com\r\nBcc: eve@example.com", + "no-at-sign", + "a@b@c.com", + "bob@localhost", + ] { + assert!( + normalize_recipients(&[bad.to_string()]).is_err(), + "accepted {bad:?}" + ); + } + } +} diff --git a/src/smtp/mod.rs b/src/smtp/mod.rs new file mode 100644 index 0000000..57fe339 --- /dev/null +++ b/src/smtp/mod.rs @@ -0,0 +1,3 @@ +pub mod compose; +pub mod tls; +pub mod worker; diff --git a/src/smtp/tls.rs b/src/smtp/tls.rs new file mode 100644 index 0000000..9d2de6b --- /dev/null +++ b/src/smtp/tls.rs @@ -0,0 +1,44 @@ +//! TLS connector for SMTP submission, trusting the OS certificate store. +//! +//! mail-send's own connector trusts only its compiled-in `webpki-roots` +//! (public CAs). IMAP goes through native-tls, which uses the OS store — so +//! without this, a self-hosted mail server with an internal-CA certificate +//! would sync fine and then fail every send on certificate verification. +//! Using the OS store here keeps both protocols trusting the same thing. + +use anyhow::{Context, Result}; +use std::sync::{Arc, OnceLock}; +use tokio_rustls::TlsConnector; + +static CONNECTOR: OnceLock = OnceLock::new(); + +pub fn connector() -> Result { + if let Some(c) = CONNECTOR.get() { + return Ok(c.clone()); + } + + let mut roots = rustls::RootCertStore::empty(); + let loaded = rustls_native_certs::load_native_certs(); + for err in &loaded.errors { + tracing::warn!(error = %err, "skipping unreadable certificate in the OS trust store"); + } + let (added, _ignored) = roots.add_parsable_certificates(loaded.certs); + anyhow::ensure!( + added > 0, + "no usable certificates in the OS trust store — SMTP TLS cannot verify any server" + ); + + // Explicit provider rather than the process default: if anything in the + // dependency tree ever enables a second rustls backend, the implicit + // default becomes ambiguous and ClientConfig::builder() panics. + let config = rustls::ClientConfig::builder_with_provider(Arc::new( + rustls::crypto::ring::default_provider(), + )) + .with_safe_default_protocol_versions() + .context("building rustls protocol config")? + .with_root_certificates(roots) + .with_no_client_auth(); + + let connector = TlsConnector::from(Arc::new(config)); + Ok(CONNECTOR.get_or_init(|| connector).clone()) +} diff --git a/src/smtp/worker.rs b/src/smtp/worker.rs new file mode 100644 index 0000000..76fb826 --- /dev/null +++ b/src/smtp/worker.rs @@ -0,0 +1,359 @@ +//! Drains the outbox: claims due items, submits them over SMTP, and either +//! records them as sent or schedules a retry (server-architecture-spec.md +//! §3.3 — never send synchronously in the request path). +//! +//! Delivery is at-least-once. If the process dies after the SMTP server has +//! accepted a message but before we record it, the item is reclaimed and +//! sent again. Reusing the same Message-ID on every attempt means that +//! duplicate is at least recognisable as the same message to recipients' +//! clients. True exactly-once isn't achievable over SMTP. + +use crate::crypto::CredentialCipher; +use crate::models::account::Account; +use crate::models::outbox::OutboxItem; +use crate::smtp::compose::{self, Draft, Sender}; +use crate::storage::BlobStore; +use anyhow::Context; +use chrono::Utc; +use mail_send::SmtpClientBuilder; +use sqlx::PgPool; +use std::sync::Arc; +use std::time::Duration; +use tokio::sync::Notify; + +pub const MAX_ATTEMPTS: i32 = 6; +const IDLE_POLL: Duration = Duration::from_secs(30); +const SMTP_TIMEOUT: Duration = Duration::from_secs(60); +/// A row still marked 'sending' this long after its last update belongs to +/// a worker that died mid-send; it's put back in the queue. +const STALE_SENDING_AFTER_MINUTES: i32 = 10; + +#[derive(Debug, PartialEq)] +pub enum Failure { + /// Worth retrying: network trouble, timeouts, 4xx "try again later". + Transient(String), + /// Retrying can't help: 5xx rejections, bad credentials, misconfigured + /// account. Failing fast shows the reader the reason immediately rather + /// than after half an hour of backoff. + Permanent(String), +} + +/// 1, 2, 4, 8, 16 minutes between attempts — about half an hour of trying +/// in total across MAX_ATTEMPTS before the item is marked failed. +pub fn retry_delay(attempts_so_far: i32) -> Duration { + let exp = attempts_so_far.clamp(1, 16) - 1; + Duration::from_secs(60 * 2u64.pow(exp as u32)).min(Duration::from_secs(30 * 60)) +} + +pub fn classify(err: &mail_send::Error) -> Failure { + use mail_send::Error as E; + let msg = err.to_string(); + match err { + E::UnexpectedReply(resp) if resp.code >= 500 => Failure::Permanent(msg), + E::UnexpectedReply(_) => Failure::Transient(msg), + E::AuthenticationFailed(_) + | E::MissingCredentials + | E::UnsupportedAuthMechanism + | E::MissingStartTls + | E::InvalidTLSName + | E::MissingMailFrom + | E::MissingRcptTo => Failure::Permanent(msg), + // Almost always an untrusted or mismatched certificate rather than + // a transient handshake hiccup — a config problem, so fail fast. + E::Tls(_) => Failure::Permanent(msg), + _ => Failure::Transient(msg), + } +} + +pub async fn run(pool: PgPool, cipher: CredentialCipher, blobs: BlobStore, wake: Arc) { + if let Err(e) = recover_stale(&pool).await { + tracing::error!(error = %e, "failed to recover stale outbox items"); + } + + loop { + match claim_next(&pool).await { + Ok(Some(item)) => { + let id = item.id; + if let Err(e) = process(&pool, &cipher, &blobs, item).await { + // Only reached if recording the outcome itself failed — + // the row stays 'sending' and recover_stale picks it up. + tracing::error!(outbox_id = %id, error = %e, "failed to record send outcome"); + } + continue; + } + Ok(None) => {} + Err(e) => tracing::error!(error = %e, "failed to claim outbox item"), + } + + tokio::select! { + _ = wake.notified() => {} + _ = tokio::time::sleep(IDLE_POLL) => {} + } + } +} + +async fn recover_stale(pool: &PgPool) -> anyhow::Result<()> { + let recovered = sqlx::query( + "UPDATE outbox SET status = 'pending', next_attempt_at = now(), updated_at = now() \ + WHERE status = 'sending' AND updated_at < now() - make_interval(mins => $1)", + ) + .bind(STALE_SENDING_AFTER_MINUTES) + .execute(pool) + .await? + .rows_affected(); + if recovered > 0 { + tracing::warn!( + recovered, + "re-queued outbox items left mid-send by a previous run" + ); + } + Ok(()) +} + +/// SKIP LOCKED so that several server instances can share one queue +/// without two of them picking up the same message. +async fn claim_next(pool: &PgPool) -> anyhow::Result> { + Ok(sqlx::query_as( + "UPDATE outbox SET status = 'sending', attempts = attempts + 1, updated_at = now() \ + WHERE id = ( \ + SELECT id FROM outbox \ + WHERE status = 'pending' AND next_attempt_at <= now() \ + ORDER BY next_attempt_at \ + FOR UPDATE SKIP LOCKED \ + LIMIT 1) \ + RETURNING *", + ) + .fetch_optional(pool) + .await?) +} + +async fn process( + pool: &PgPool, + cipher: &CredentialCipher, + blobs: &BlobStore, + item: OutboxItem, +) -> anyhow::Result<()> { + match send(pool, cipher, &item).await { + Ok((bytes, sender_email, sender_name)) => { + record_sent( + pool, + blobs, + &item, + &bytes, + &sender_email, + sender_name.as_deref(), + ) + .await + } + Err(Failure::Permanent(reason)) => record_failed(pool, &item, &reason).await, + Err(Failure::Transient(reason)) if item.attempts >= MAX_ATTEMPTS => { + record_failed( + pool, + &item, + &format!("gave up after {} attempts: {reason}", item.attempts), + ) + .await + } + Err(Failure::Transient(reason)) => { + let delay = retry_delay(item.attempts); + tracing::warn!(outbox_id = %item.id, attempt = item.attempts, ?delay, %reason, "send failed, will retry"); + sqlx::query( + "UPDATE outbox SET status = 'pending', last_error = $2, updated_at = now(), \ + next_attempt_at = now() + make_interval(secs => $3) WHERE id = $1", + ) + .bind(item.id) + .bind(&reason) + .bind(delay.as_secs_f64()) + .execute(pool) + .await?; + Ok(()) + } + } +} + +async fn send( + pool: &PgPool, + cipher: &CredentialCipher, + item: &OutboxItem, +) -> Result<(Vec, String, Option), Failure> { + let account: Account = sqlx::query_as("SELECT * FROM accounts WHERE id = $1") + .bind(item.account_id) + .fetch_one(pool) + .await + .map_err(|e| Failure::Transient(format!("loading account: {e}")))?; + + let sender_email = account.sender_address().ok_or_else(|| { + Failure::Permanent( + "account has no sender address — set email_address on the account".into(), + ) + })?; + + let message_id = item + .message_id + .clone() + .ok_or_else(|| Failure::Permanent("queued without a Message-ID".into()))?; + + let draft = Draft { + to: &item.to_addrs, + cc: &item.cc_addrs, + bcc: &item.bcc_addrs, + subject: &item.subject, + text_body: &item.text_body, + message_id: &message_id, + in_reply_to: item.in_reply_to.as_deref(), + references: &item.references_, + date_unix: Utc::now().timestamp(), + }; + let sender = Sender { + email: &sender_email, + display_name: account.display_name.as_deref(), + }; + let (bytes, envelope) = compose::render(&sender, &draft) + .map_err(|e| Failure::Permanent(format!("rendering message: {e}")))?; + + let password = cipher + .decrypt(&account.encrypted_password, &account.password_nonce) + .map_err(|e| Failure::Permanent(format!("decrypting SMTP password: {e}")))?; + + let connector = crate::smtp::tls::connector().map_err(|e| Failure::Permanent(e.to_string()))?; + + // Port 587 with STARTTLS is the spec's default (§3.3); implicit TLS + // (typically 465) when STARTTLS is off. Never plaintext — mail-send's + // connect() returns a TLS-typed client and errors with MissingStartTls + // rather than falling back. + let mut builder = SmtpClientBuilder::new(account.smtp_host.clone(), account.smtp_port as u16) + .implicit_tls(!account.smtp_use_starttls) + .credentials((account.username.clone(), password)) + .timeout(SMTP_TIMEOUT); + builder.tls_connector = connector; + + let message = mail_send::smtp::message::Message { + mail_from: envelope.mail_from.clone().into(), + rcpt_to: envelope.rcpt_to.iter().map(|r| r.clone().into()).collect(), + body: bytes.clone().into(), + }; + + let mut client = builder.connect().await.map_err(|e| classify(&e))?; + client.send(message).await.map_err(|e| classify(&e))?; + let _ = client.quit().await; + + Ok((bytes, sender_email, account.display_name)) +} + +/// Puts the sent message into the thread it belongs to, in the same +/// transaction that marks the outbox item sent — so there's never a moment +/// where it's recorded as sent but missing from the conversation. +async fn record_sent( + pool: &PgPool, + blobs: &BlobStore, + item: &OutboxItem, + bytes: &[u8], + sender_email: &str, + sender_name: Option<&str>, +) -> anyhow::Result<()> { + let (_, raw_ref) = blobs + .put(bytes) + .await + .context("storing sent message blob")?; + + let mut tx = pool.begin().await?; + + let (message_row_id,): (uuid::Uuid,) = sqlx::query_as( + r#"INSERT INTO messages + (account_id, uid, source, message_id, in_reply_to, references_, thread_id, + from_addr, from_name, to_addrs, cc_addrs, subject, sent_at, flags, + body_fetched, raw_blob_ref) + VALUES ($1, NULL, 'sent', $2, $3, $4, COALESCE($5, gen_random_uuid()), + $6, $7, $8, $9, $10, now(), ARRAY['\Seen'], true, $11) + RETURNING id"#, + ) + .bind(item.account_id) + .bind(item.message_id.as_deref().map(compose::bare_id)) + .bind(&item.in_reply_to) + .bind(&item.references_) + .bind(item.thread_id) + .bind(sender_email) + .bind(sender_name) + .bind(&item.to_addrs) + .bind(&item.cc_addrs) + .bind(&item.subject) + .bind(&raw_ref) + .fetch_one(&mut *tx) + .await?; + + sqlx::query("INSERT INTO bodies (message_id, text_body, html_body) VALUES ($1, $2, NULL)") + .bind(message_row_id) + .bind(&item.text_body) + .execute(&mut *tx) + .await?; + + sqlx::query( + "UPDATE outbox SET status = 'sent', sent_at = now(), updated_at = now(), \ + last_error = NULL, sent_message_id = $2 WHERE id = $1", + ) + .bind(item.id) + .bind(message_row_id) + .execute(&mut *tx) + .await?; + + tx.commit().await?; + tracing::info!(outbox_id = %item.id, recipients = item.to_addrs.len() + item.cc_addrs.len() + item.bcc_addrs.len(), "message sent"); + Ok(()) +} + +async fn record_failed(pool: &PgPool, item: &OutboxItem, reason: &str) -> anyhow::Result<()> { + tracing::warn!(outbox_id = %item.id, %reason, "send failed permanently"); + sqlx::query( + "UPDATE outbox SET status = 'failed', last_error = $2, updated_at = now() WHERE id = $1", + ) + .bind(item.id) + .bind(reason) + .execute(pool) + .await?; + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn backoff_doubles_and_caps() { + let mins: Vec = (1..=MAX_ATTEMPTS) + .map(|a| retry_delay(a).as_secs() / 60) + .collect(); + assert_eq!(mins, vec![1, 2, 4, 8, 16, 30]); + assert_eq!(retry_delay(40), Duration::from_secs(30 * 60)); + } + + fn reply(code: u16) -> mail_send::Error { + mail_send::Error::UnexpectedReply(smtp_proto::Response { + code, + esc: [0, 0, 0], + message: String::new(), + }) + } + + #[test] + fn five_hundreds_are_permanent_four_hundreds_retry() { + assert!(matches!(classify(&reply(550)), Failure::Permanent(_))); + assert!(matches!(classify(&reply(421)), Failure::Transient(_))); + assert!(matches!(classify(&reply(451)), Failure::Transient(_))); + } + + #[test] + fn network_trouble_retries_config_trouble_does_not() { + assert!(matches!( + classify(&mail_send::Error::Timeout), + Failure::Transient(_) + )); + assert!(matches!( + classify(&mail_send::Error::Io(std::io::Error::other("reset"))), + Failure::Transient(_) + )); + assert!(matches!( + classify(&mail_send::Error::MissingStartTls), + Failure::Permanent(_) + )); + } +} diff --git a/tests/routes.rs b/tests/routes.rs index 390517c..6ed337c 100644 --- a/tests/routes.rs +++ b/tests/routes.rs @@ -35,6 +35,7 @@ fn test_router() -> axum::Router { blob_storage_dir: std::path::PathBuf::from("/tmp/tern-test"), session_ttl_hours: 1, }, + outbox_wake: std::sync::Arc::new(tokio::sync::Notify::new()), }; tern_server::api::build(state) @@ -58,6 +59,10 @@ async fn parameterised_routes_match() { ("GET", format!("/api/messages/{id}")), ("GET", format!("/api/threads/{id}")), ("DELETE", format!("/api/accounts/{id}")), + ("POST", format!("/api/threads/{id}/read")), + ("PUT", format!("/api/outbox/{id}")), + ("DELETE", format!("/api/outbox/{id}")), + ("POST", format!("/api/outbox/{id}/send")), ] { let status = status_for(method, &uri).await; assert_ne!( @@ -77,6 +82,7 @@ async fn collection_routes_match() { "/api/messages", "/api/threads", "/api/events", + "/api/outbox", ] { let status = status_for("GET", uri).await; assert_ne!(