4 Commits
Author SHA1 Message Date
Mateusz PstruchaandClaude Opus 5.5 d839d57e11 Bump to 0.4.0
CI / test (push) Successful in 2m49s
Release / image (push) Successful in 2m35s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-23 11:05:56 +02:00
Mateusz PstruchaandClaude Opus 5.5 fd8ee8311c Add sending: outbox queue, SMTP worker, drafts
CI / test (push) Successful in 2m28s
Drafts and queued sends are one outbox row in different states, drained
by a background worker so SMTP never runs in the request path (§3.3).
Retries back off 1-16 min; 5xx, auth and TLS failures fail fast; items
a crashed worker left mid-send are reclaimed. Each message keeps its
Message-ID across retries, so an at-least-once duplicate is recognisable.
Reply headers are derived server-side from the parent, and sent mail is
filed into its thread alongside received mail.

Three things the libraries would have got wrong:
- mail-builder's .bcc() writes an ordinary Bcc header every recipient
  sees. Bcc goes in the envelope only; a test checks it never reaches the
  rendered bytes, and was confirmed to fail if .bcc() is reintroduced.
- mail-send trusts only compiled-in public CAs, while IMAP (native-tls)
  uses the OS store — a server with an internal-CA cert would sync but
  never send. SMTP now uses the OS store too.
- rustls is added with default-features off: its defaults pull in
  aws-lc-rs, which needs cmake/clang and would break the runner build.

Also fixes: UIDVALIDITY resets now only delete IMAP-sourced rows (sent
mail shares the table and exists nowhere else); first sync no longer
logs a false "UIDVALIDITY changed" warning; Message-IDs are stored bare
whichever path writes them (ENVELOPE brackets them, mail-parser doesn't);
accounts can choose STARTTLS vs implicit TLS for SMTP, defaulting by port.

Verified end to end against a TLS mail server with a private-CA cert,
with no plaintext patching: IMAPS sync, SMTPS send, delivery and headers
checked from the recipients' mailboxes, Bcc absent from other copies,
plaintext refused when STARTTLS is unavailable, retry scheduling on
connection failure.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-23 10:59:28 +02:00
Mateusz PstruchaandClaude Opus 5 bc39a1221c Add thread listing, fix dead path routes
CI / test (push) Successful in 29s
Adds GET /api/threads, grouped server-side: 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. The
thread detail endpoint now returns bodies too, so opening a conversation
is one request rather than one per message.

Fixes three routes that have been dead since the first commit. axum 0.7
spells a path parameter ':id'; '{id}' is axum 0.8 syntax and was being
matched as a literal segment, so GET /api/messages/<id>, GET
/api/threads/<id> and DELETE /api/accounts/<id> all 404'd. This fails
silently — no compile or startup error — and the original smoke test
only exercised list endpoints. Found by clicking a conversation in the
webapp.

Adds tests/routes.rs to cover route shape, verified to fail against the
old syntax.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-22 22:53:13 +02:00
Mateusz PstruchaandClaude Opus 5 6c73a91b8e Quieten docker build output in release logs
CI / test (push) Successful in 41s
The v0.2.0 release log was 17k lines, ~12k of which were BuildKit's
animated progress display repainting itself with cursor-movement
escapes. --progress=plain emits one line per event instead.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-22 22:23:34 +02:00
24 changed files with 1454 additions and 21 deletions

No files matched your search

+7 -1
View File
@@ -30,10 +30,16 @@ jobs:
-u '${{ gitea.actor }}' --password-stdin
- name: Build and push image
env:
DOCKER_BUILDKIT: '1'
run: |
IMAGE='${{ steps.meta.outputs.image }}'
VERSION='${{ steps.meta.outputs.version }}'
docker build -t "$IMAGE:$VERSION" -t "$IMAGE:latest" .
# --progress=plain: without it BuildKit renders an animated TTY
# progress display, repainting every step on each frame. In a log
# file that became ~15k lines of cursor-movement escapes for a
# build that only has a few hundred lines of real output.
docker build --progress=plain -t "$IMAGE:$VERSION" -t "$IMAGE:latest" .
docker push "$IMAGE:$VERSION"
docker push "$IMAGE:latest"
Generated
+17 -1
View File
@@ -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"
@@ -2663,7 +2675,7 @@ dependencies = [
[[package]]
name = "tern-server"
version = "0.2.0"
version = "0.4.0"
dependencies = [
"anyhow",
"argon2",
@@ -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",
+10 -1
View File
@@ -1,6 +1,6 @@
[package]
name = "tern-server"
version = "0.2.0"
version = "0.4.0"
edition = "2021"
description = "Tern sync server — the only component that speaks IMAP/SMTP"
@@ -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"
+17 -3
View File
@@ -2,19 +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.
+51
View File
@@ -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);
+15 -2
View File
@@ -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<String>,
pub display_name: Option<String>,
/// 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<bool>,
}
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?;
+19 -2
View File
@@ -97,11 +97,14 @@ pub async fn get(
/// "Fetch thread" endpoint (§3.6) — the client just needs thread_id exposed
/// plus a way to pull every message in it; how to render it (collapsed vs
/// flat) is left entirely to the client.
///
/// Bodies are included so opening a conversation is one request rather than
/// one per message.
pub async fn get_thread(
State(state): State<AppState>,
user: CurrentUser,
Path(thread_id): Path<Uuid>,
) -> ApiResult<Json<Vec<Message>>> {
) -> ApiResult<Json<Vec<MessageDetail>>> {
let messages: Vec<Message> = sqlx::query_as(
"SELECT m.* FROM messages m JOIN accounts a ON a.id = m.account_id \
WHERE m.thread_id = $1 AND a.user_id = $2 \
@@ -112,5 +115,19 @@ pub async fn get_thread(
.fetch_all(&state.pool)
.await?;
Ok(Json(messages))
let ids: Vec<Uuid> = messages.iter().map(|m| m.id).collect();
let bodies: Vec<Body> = sqlx::query_as("SELECT * FROM bodies WHERE message_id = ANY($1)")
.bind(&ids)
.fetch_all(&state.pool)
.await?;
let detailed = messages
.into_iter()
.map(|message| {
let body = bodies.iter().find(|b| b.message_id == message.id).cloned();
MessageDetail { message, body }
})
.collect();
Ok(Json(detailed))
}
+2
View File
@@ -4,8 +4,10 @@ pub mod events;
pub mod folders;
pub mod messages;
pub mod middleware;
pub mod outbox;
pub mod router;
pub mod state;
pub mod threads;
pub use router::build;
pub use state::AppState;
+267
View File
@@ -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<Uuid>,
#[serde(default)]
pub to: Vec<String>,
#[serde(default)]
pub cc: Vec<String>,
#[serde(default)]
pub bcc: Vec<String>,
#[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<Uuid>,
/// false = save as draft, true = queue for sending.
#[serde(default)]
pub send: bool,
}
#[derive(Deserialize)]
pub struct UpdateDraftRequest {
pub to: Vec<String>,
pub cc: Vec<String>,
pub bcc: Vec<String>,
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<AppState>,
user: CurrentUser,
) -> ApiResult<Json<Vec<OutboxItem>>> {
let items: Vec<OutboxItem> = 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<AppState>,
user: CurrentUser,
Json(req): Json<ComposeRequest>,
) -> ApiResult<Json<OutboxItem>> {
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<AppState>,
user: CurrentUser,
Path(id): Path<Uuid>,
Json(req): Json<UpdateDraftRequest>,
) -> ApiResult<Json<OutboxItem>> {
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<OutboxItem> = 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<AppState>,
user: CurrentUser,
Path(id): Path<Uuid>,
) -> ApiResult<Json<OutboxItem>> {
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<AppState>,
user: CurrentUser,
Path(id): Path<Uuid>,
) -> ApiResult<Json<serde_json::Value>> {
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<OutboxItem> {
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<String> {
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<Account> {
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<Message> {
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"
))
}
+13 -5
View File
@@ -1,6 +1,6 @@
use crate::api::state::AppState;
use crate::api::{accounts, auth, events, folders, messages};
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;
@@ -10,11 +10,19 @@ pub fn build(state: AppState) -> Router {
.route("/api/auth/register", post(auth::register))
.route("/api/auth/login", post(auth::login))
.route("/api/accounts", get(accounts::list).post(accounts::create))
.route("/api/accounts/{id}", delete(accounts::delete))
.route("/api/accounts/:id", delete(accounts::delete))
.route("/api/folders", get(folders::list).post(folders::create))
.route("/api/messages", get(messages::list))
.route("/api/messages/{id}", get(messages::get))
.route("/api/threads/{id}", get(messages::get_thread))
.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())
+5
View File
@@ -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<Notify>,
}
+117
View File
@@ -0,0 +1,117 @@
//! Thread-grouped listing — one row per conversation, which is how both
//! clients render the inbox.
//!
//! This has to be grouped server-side: a thread's messages are spread
//! through the flat message list by date, so a client grouping one page at a
//! time would split threads across page boundaries and miscount unread.
//!
//! Cursor is the thread's `last_message_at`, matching the cursor-based
//! (not offset) approach in server-architecture-spec.md §4.
use crate::api::middleware::CurrentUser;
use crate::api::state::AppState;
use crate::error::ApiResult;
use axum::{
extract::{Query, State},
Json,
};
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use uuid::Uuid;
#[derive(Deserialize)]
pub struct ListThreadsQuery {
pub folder_id: Option<Uuid>,
pub before: Option<DateTime<Utc>>,
pub limit: Option<i64>,
}
#[derive(Debug, Serialize, sqlx::FromRow)]
pub struct ThreadSummary {
pub thread_id: Uuid,
pub subject: Option<String>,
/// Display name (falling back to address) of the most recent sender.
pub last_from: Option<String>,
pub last_message_at: Option<DateTime<Utc>>,
pub message_count: i64,
pub unread_count: i64,
pub has_attachments: bool,
}
#[derive(Serialize)]
pub struct ListThreadsResponse {
pub threads: Vec<ThreadSummary>,
pub next_cursor: Option<DateTime<Utc>>,
}
pub async fn list(
State(state): State<AppState>,
user: CurrentUser,
Query(q): Query<ListThreadsQuery>,
) -> ApiResult<Json<ListThreadsResponse>> {
let limit = q.limit.unwrap_or(50).clamp(1, 200);
let before = q.before.unwrap_or_else(Utc::now);
// Subject comes from the oldest message (the one that started the
// thread); sender and timestamp from the newest, which is what a list
// row should show. Unread is "no \Seen flag" — flags are stored in IMAP
// wire format, so the comparison is against the literal '\Seen'.
let threads: Vec<ThreadSummary> = sqlx::query_as(
r#"
SELECT
m.thread_id,
(ARRAY_AGG(m.subject ORDER BY m.sent_at ASC NULLS LAST))[1] AS subject,
(ARRAY_AGG(COALESCE(NULLIF(m.from_name, ''), m.from_addr)
ORDER BY m.sent_at DESC NULLS LAST))[1] AS last_from,
MAX(m.sent_at) AS last_message_at,
COUNT(*) AS message_count,
COUNT(*) FILTER (WHERE NOT ('\Seen' = ANY(m.flags))) AS unread_count,
BOOL_OR(EXISTS (SELECT 1 FROM attachments att WHERE att.message_id = m.id))
AS has_attachments
FROM messages m
JOIN accounts a ON a.id = m.account_id
WHERE a.user_id = $1
AND ($2::uuid IS NULL OR m.folder_id = $2)
GROUP BY m.thread_id
HAVING MAX(m.sent_at) < $3
ORDER BY last_message_at DESC
LIMIT $4
"#,
)
.bind(user.user_id)
.bind(q.folder_id)
.bind(before)
.bind(limit)
.fetch_all(&state.pool)
.await?;
let next_cursor = threads.last().and_then(|t| t.last_message_at);
Ok(Json(ListThreadsResponse {
threads,
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<AppState>,
user: CurrentUser,
axum::extract::Path(thread_id): axum::extract::Path<Uuid>,
) -> ApiResult<Json<serde_json::Value>> {
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 })))
}
+24 -5
View File
@@ -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<String> = 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)
+1
View File
@@ -6,4 +6,5 @@ pub mod db;
pub mod error;
pub mod imap_sync;
pub mod models;
pub mod smtp;
pub mod storage;
+9
View File
@@ -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);
+18
View File
@@ -18,6 +18,20 @@ pub struct Account {
pub encrypted_password: Vec<u8>,
pub password_nonce: Vec<u8>,
pub created_at: DateTime<Utc>,
pub email_address: Option<String>,
pub display_name: Option<String>,
}
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<String> {
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<String>,
pub display_name: Option<String>,
pub created_at: DateTime<Utc>,
}
@@ -45,6 +61,8 @@ impl From<Account> 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,
}
}
+4 -1
View File
@@ -7,7 +7,8 @@ pub struct Message {
pub id: Uuid,
pub account_id: Uuid,
pub folder_id: Option<Uuid>,
pub uid: i64,
/// None for mail sent from Tern, which never came from IMAP.
pub uid: Option<i64>,
pub message_id: Option<String>,
pub in_reply_to: Option<String>,
pub references_: Vec<String>,
@@ -22,6 +23,8 @@ pub struct Message {
pub spam_score: Option<f32>,
pub body_fetched: bool,
pub raw_blob_ref: Option<String>,
/// 'imap' for synced mail, 'sent' for mail sent from Tern.
pub source: String,
pub created_at: DateTime<Utc>,
}
+1
View File
@@ -1,6 +1,7 @@
pub mod account;
pub mod folder;
pub mod message;
pub mod outbox;
pub mod user;
pub use account::Account;
+27
View File
@@ -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<String>,
pub cc_addrs: Vec<String>,
pub bcc_addrs: Vec<String>,
pub subject: String,
pub text_body: String,
pub in_reply_to: Option<String>,
pub references_: Vec<String>,
pub thread_id: Option<Uuid>,
pub message_id: Option<String>,
pub attempts: i32,
pub last_error: Option<String>,
pub next_attempt_at: Option<DateTime<Utc>>,
pub sent_message_id: Option<Uuid>,
pub created_at: DateTime<Utc>,
pub updated_at: DateTime<Utc>,
pub sent_at: Option<DateTime<Utc>>,
}
+316
View File
@@ -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<String>,
}
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<Vec<String>, String> {
let mut out: Vec<String> = 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<String>, Vec<String>) {
const MAX_REFERENCES: usize = 20;
let parent = parent_message_id.map(bare_id).filter(|id| !id.is_empty());
let mut refs: Vec<String> = 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<u8>, 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::<Vec<_>>(),
);
}
let bytes = builder.write_to_vec()?;
let mut rcpt_to: Vec<String> = 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: <parent@example.com>"), "{text}");
assert!(
text.contains("<root@example.com>") && text.contains("References:"),
"{text}"
);
assert!(text.contains("Message-ID: <abc@example.com>"), "{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> "), "abc@x.y");
assert_eq!(bare_id("abc@x.y"), "abc@x.y");
}
#[test]
fn reply_headers_chain_parent_onto_references() {
let refs = vec!["<root@x>".to_string()];
let (irt, chain) = reply_headers(Some("<parent@x>"), &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<String> = (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>",
"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:?}"
);
}
}
}
+3
View File
@@ -0,0 +1,3 @@
pub mod compose;
pub mod tls;
pub mod worker;
+44
View File
@@ -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<TlsConnector> = OnceLock::new();
pub fn connector() -> Result<TlsConnector> {
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())
}
+359
View File
@@ -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<Notify>) {
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<Option<OutboxItem>> {
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<u8>, String, Option<String>), 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<u64> = (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(_)
));
}
}
+108
View File
@@ -0,0 +1,108 @@
//! Route-shape tests.
//!
//! These exist because path-parameter syntax is version-specific and fails
//! silently: axum 0.7 spells a parameter `:id`, while 0.8 spells it `{id}`.
//! Using the wrong one doesn't error at compile time or startup — the router
//! just treats it as a literal segment and every request 404s. Three
//! endpoints shipped broken that way, and a list-endpoint smoke test didn't
//! notice.
//!
//! A 404 here means the route isn't matching. Any other status (401 without
//! credentials, 500 with no database) means it matched, which is all these
//! assert.
use axum::body::Body;
use axum::http::{Request, StatusCode};
use tower::ServiceExt;
/// Builds the real router against a lazily-connected pool. The pool is never
/// used, because every request under test stops at the auth extractor or the
/// router itself — but it has to be a real `PgPool` to construct AppState.
fn test_router() -> axum::Router {
let pool = sqlx::postgres::PgPoolOptions::new()
.connect_lazy("postgres://tern:tern@127.0.0.1:1/placeholder")
.expect("lazy pool");
let state = tern_server::api::AppState {
pool,
cipher: tern_server::crypto::CredentialCipher::new(&[0u8; 32]),
blobs: tern_server::storage::BlobStore::new(std::path::PathBuf::from("/tmp/tern-test")),
session_ttl_hours: 1,
config: tern_server::config::Config {
database_url: String::new(),
bind_addr: String::new(),
credential_key: [0u8; 32],
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)
}
async fn status_for(method: &str, uri: &str) -> StatusCode {
let request = Request::builder()
.method(method)
.uri(uri)
.body(Body::empty())
.unwrap();
test_router().oneshot(request).await.unwrap().status()
}
#[tokio::test]
async fn parameterised_routes_match() {
let id = "4f6cf11f-da82-49cf-9988-7b450b97a1c3";
for (method, uri) in [
("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!(
status,
StatusCode::NOT_FOUND,
"{method} {uri} did not match any route — check the path parameter syntax \
against the axum version in Cargo.toml"
);
}
}
#[tokio::test]
async fn collection_routes_match() {
for uri in [
"/api/accounts",
"/api/folders",
"/api/messages",
"/api/threads",
"/api/events",
"/api/outbox",
] {
let status = status_for("GET", uri).await;
assert_ne!(
status,
StatusCode::NOT_FOUND,
"GET {uri} did not match any route"
);
}
}
#[tokio::test]
async fn healthz_is_public() {
assert_eq!(status_for("GET", "/healthz").await, StatusCode::OK);
}
#[tokio::test]
async fn unknown_route_still_404s() {
assert_eq!(
status_for("GET", "/api/nope").await,
StatusCode::NOT_FOUND,
"sanity check: a genuinely missing route should 404"
);
}