8 Commits
Author SHA1 Message Date
Mateusz PstruchaandClaude Opus 5.5 4b6eeaca15 Bump to 0.5.0
CI / test (push) Successful in 3m51s
Release / image (push) Successful in 2m48s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-23 12:01:40 +02:00
Mateusz PstruchaandClaude Opus 5.5 3f1d9227c6 Add trash retention, stop-after-match and run-now
CI / test (push) Successful in 46s
Mail in Trash is purged after TRASH_RETENTION_DAYS (default 30, 0
disables), hourly. Stored files are content-addressed and shared, so a
file is only removed once nothing references it — and not if written or
reused in the last hour, since ingest writes a file before inserting the
row that points at it. Reusing an existing blob now refreshes its mtime
so that grace period protects it too. Trash rows report when they purge.

"Stop processing further rules" moves from an action to a per-rule
option (stop_after_match): it's a property of the rule, not something
done to a message. Migration 0007 converts existing stop actions, and a
stop submitted as an action is now rejected.

Rules can be run now against existing mail outside Trash, disabled ones
included so a rule can be tried before it's switched on. It pages by
key, one transaction per page, and only re-reads stored raw messages
when the rule tests a header.

All JSON bodies now go through an AppJson extractor so malformed or
mistyped bodies return the API's {"error": …} shape. Axum's default was
a plain-text 422 the webapp could only show as "request failed: 422" —
losing the useful part, e.g. "unknown variant `stop`".

Verified live: the stop flag blocks a lower rule on arriving mail; run
now on a disabled header rule archived 2 of 4 messages; a purge removed
an expired message and its unique raw file while keeping an attachment
file still shared with a live copy, with no orphaned rows.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-23 12:00:04 +02:00
Mateusz PstruchaandClaude Opus 5.5 5809c9e310 Document threading, tags and rules behaviour
CI / test (push) Successful in 50s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-23 11:26:03 +02:00
Mateusz PstruchaandClaude Opus 5.5 807775726c Add threading, tags, rules and thread actions
CI / test (push) Successful in 3m3s
Threading (§3.6) is an incremental, database-backed JWZ: each message
links to its ancestors, to replies that arrived before it, and to
siblings sharing a missing ancestor (what JWZ's placeholder containers
do), merging every thread it touches into the one holding the oldest
message. Subject-only grouping applies only to Re:/Fwd: messages with no
reference headers, so lists that strip References still thread while
unrelated mail sharing a generic subject never merges. Existing mail is
re-threaded once per account via a versioned backfill.

Rules (§3.5) are structured JSON — one level of all/any tests, exactly
what the editor can show — run after the body is fetched since they need
headers. Every matching rule applies in priority order until a `stop`.
Patterns use the regex crate: linear-time, so a user-written pattern run
against every incoming message can't hang ingest. Numeric comparison
reads the first number in a value, so both "5.3" and "Yes, score=5.3"
spam headers work for phase 6.

Rule "delete" is a soft delete to Trash: a rule with an over-broad
pattern must not be able to destroy mail. Archive moves to a system
folder found by role, so renaming it doesn't break archiving. Manual
thread actions use the same action type and applier as rules, so the two
can't drift.

Thread listing now takes a view (inbox/all/sent/trash/folder/tag). A
thread appears in a view if any message matches, but the row summarises
the whole conversation — so a reply to an archived thread brings it back
to the inbox. Row subjects come from the root when present, not merely
the earliest Date (replies can be dated earlier, and Date ties are
common at one-second resolution).

Verified against a live TLS mail server: out-of-order parent/reply,
replies to a missing root, a list that strips References, and two
unrelated "Invoice" mails kept apart; rules tagging, archiving, trashing
on spam score, and `stop` blocking a lower rule; the backfill rebuilding
the same 9 threads from 13 split messages.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-23 11:19:35 +02:00
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
40 changed files with 3481 additions and 34 deletions

No files matched your search

+3
View File
@@ -13,4 +13,7 @@ CREDENTIAL_KEY=
BLOB_STORAGE_DIR=./data/blobs
SESSION_TTL_HOURS=720
# Days mail stays in Trash before it's permanently deleted. 0 disables purging.
TRASH_RETENTION_DAYS=30
RUST_LOG=tern_server=debug,tower_http=debug
+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
+30 -1
View File
@@ -1981,6 +1981,18 @@ dependencies = [
"bitflags",
]
[[package]]
name = "regex"
version = "1.13.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f020237b6c8eed93db2e2cb53c00c60a8e1bc73da7d073199a1180401450218d"
dependencies = [
"aho-corasick",
"memchr",
"regex-automata",
"regex-syntax",
]
[[package]]
name = "regex-automata"
version = "0.4.18"
@@ -2077,6 +2089,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 +2687,7 @@ dependencies = [
[[package]]
name = "tern-server"
version = "0.2.0"
version = "0.5.0"
dependencies = [
"anyhow",
"argon2",
@@ -2679,12 +2703,17 @@ dependencies = [
"mail-parser 0.11.9",
"mail-send",
"rand",
"regex",
"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",
+11 -1
View File
@@ -1,6 +1,6 @@
[package]
name = "tern-server"
version = "0.2.0"
version = "0.5.0"
edition = "2021"
description = "Tern sync server — the only component that speaks IMAP/SMTP"
@@ -16,6 +16,14 @@ 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"
regex = "1"
serde = { version = "1", features = ["derive"] }
serde_json = "1"
@@ -39,3 +47,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"
+34 -3
View File
@@ -2,19 +2,50 @@
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–5)
- **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.
- **Threading** (`src/threading.rs`, §3.6) — an incremental, database-backed JWZ. Each message links to its ancestors, to replies that arrived before it, and to siblings sharing a *missing* ancestor (what JWZ's placeholder containers do), merging every thread it touches into the one holding the oldest message. Subject-only grouping applies only to `Re:`/`Fwd:` messages with no reference headers — lists that strip References still thread, while unrelated mail sharing a generic subject never merges. Existing mail is re-threaded once per account via a versioned backfill (`THREADING_VERSION`).
- **Tags, folders and views** — thread listing takes `view=inbox|all|sent|trash|folder|tag`. A thread appears in a view if any of its messages does, but the row summarises the whole conversation, so a reply to an archived thread brings it back to the inbox. Archive is a system folder found by role, so it can be renamed.
- **Rules** (`src/rules.rs`, `/api/rules`, §3.5) — structured JSON: one level of all/any tests (from, to, cc, recipients, subject, body, any header; contains, is, regex, exists, greater/less than) and an action list (tag, move, archive, mark read, delete). Run on new mail after its body is fetched; every matching rule applies in priority order, until one marked *stop after match*. Any rule can also be **run now** against existing mail (`POST /api/rules/:id/run`) — disabled ones too, so a rule can be tried before it's switched on. Manual thread actions (`POST /api/threads/:id/actions`) use the same action format and code.
## How rules behave
- **Delete moves to Trash.** A rule runs on every incoming message, so one with an over-broad pattern must not be able to destroy mail. Trashed mail can be restored until it's purged — see below.
- **Patterns can't hang ingest.** The `regex` crate matches in linear time (no catastrophic backtracking), and patterns are size-capped and validated when the rule is saved.
- **Numeric comparisons read the first number in a value**, so both `X-Spam-Score: 5.3` and `X-Spam-Status: Yes, score=5.3` work — ready for phase 6's PMG headers.
- **Run now** covers everything outside Trash, including mail already filed away, and skips sent mail (rules are for incoming mail). Stored raw messages are only re-read when the rule tests a header, so body/subject/sender rules stay a fast database scan.
- **Rules see a message a moment after it appears.** Headers sync first so new mail shows quickly; rules need the full headers and body, so they run once the body arrives, seconds later.
- **No notify/don't-notify action yet** — it arrives with the notification work in phases 7–8.
## Trash retention
Mail in Trash is permanently deleted after `TRASH_RETENTION_DAYS` (default 30; `0` disables purging), checked hourly. Stored files are content-addressed and shared between identical messages or attachments, so a file is only removed once nothing references it — and not if it was written or reused in the last hour, which covers the gap between ingest writing a file and inserting the row that points at it.
Purged mail doesn't come back: the sync engine only fetches UIDs above the last one it has seen. The exception is a UIDVALIDITY reset, which re-syncs the whole INBOX.
## 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: spam header rules (the rule engine already supports them — phase 6 is about defaults and a UI for the threshold), 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.
- **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);
+36
View File
@@ -0,0 +1,36 @@
-- Phase 5: tags, rules, threading (server-architecture-spec.md §3.5, §3.6).
-- Soft delete. A rule runs on every incoming message, so one with an
-- over-broad pattern must not be able to destroy mail: "delete" moves it to
-- Trash, where it can be restored.
ALTER TABLE messages ADD COLUMN deleted_at TIMESTAMPTZ;
-- Subject with Re:/Fwd:/[list] prefixes stripped, for the threading
-- fallback that groups replies whose reference headers were removed.
ALTER TABLE messages ADD COLUMN subject_norm TEXT;
CREATE INDEX messages_account_subject_norm_idx ON messages (account_id, subject_norm);
-- Threading looks up messages by ID and by overlapping References.
CREATE INDEX messages_account_message_id_idx ON messages (account_id, message_id);
CREATE INDEX messages_references_gin_idx ON messages USING GIN (references_);
-- Normalise any Message-IDs stored bracketed before ingest normalised them
-- (IMAP ENVELOPE returns them bracketed, mail-parser bare). Threading
-- compares these for equality, so both forms must not coexist.
UPDATE messages SET
message_id = btrim(message_id, '<> '),
in_reply_to = btrim(in_reply_to, '<> '),
references_ = ARRAY(SELECT btrim(r, '<> ') FROM unnest(references_) AS r);
-- System folders are found by role rather than name, so renaming the
-- Archive folder doesn't break archiving.
ALTER TABLE folders ADD COLUMN role TEXT CHECK (role IN ('archive'));
CREATE UNIQUE INDEX folders_user_role_idx ON folders (user_id, role) WHERE role IS NOT NULL;
-- Tag colours are rendered into the UI, so only plain hex is allowed.
ALTER TABLE tags ADD CONSTRAINT tags_color_hex CHECK (color IS NULL OR color ~ '^#[0-9a-fA-F]{6}$');
-- Bumped whenever the threading algorithm changes. An account below the
-- current version has its existing mail re-threaded once, on the next
-- sync start.
ALTER TABLE sync_state ADD COLUMN threading_version INTEGER NOT NULL DEFAULT 0;
+13
View File
@@ -0,0 +1,13 @@
-- "Stop processing further rules" is a property of a rule, not something
-- it does to a message, so it moves out of the action list into a column.
ALTER TABLE rules ADD COLUMN stop_after_match BOOLEAN NOT NULL DEFAULT false;
UPDATE rules SET
stop_after_match = true,
actions = COALESCE(
(SELECT jsonb_agg(a) FROM jsonb_array_elements(actions) AS a WHERE a->>'type' <> 'stop'),
'[]'::jsonb)
WHERE actions @> '[{"type": "stop"}]';
-- Trashed mail is purged after a retention period; the purge scans by age.
CREATE INDEX messages_deleted_at_idx ON messages (deleted_at) WHERE deleted_at IS NOT NULL;
+17 -4
View File
@@ -1,6 +1,6 @@
use crate::api::middleware::CurrentUser;
use crate::api::state::AppState;
use crate::error::ApiResult;
use crate::error::{ApiResult, AppJson};
use crate::models::account::{Account, AccountPublic};
use axum::{extract::State, Json};
use serde::Deserialize;
@@ -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(
@@ -35,14 +43,16 @@ pub async fn list(
pub async fn create(
State(state): State<AppState>,
user: CurrentUser,
Json(req): Json<CreateAccountRequest>,
AppJson(req): AppJson<CreateAccountRequest>,
) -> ApiResult<Json<AccountPublic>> {
let encrypted = state.cipher.encrypt(&req.password)?;
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?;
+3 -3
View File
@@ -1,6 +1,6 @@
use crate::api::state::AppState;
use crate::auth::{hash_password, verify_password};
use crate::error::{ApiError, ApiResult};
use crate::error::{ApiError, ApiResult, AppJson};
use crate::models::User;
use axum::{extract::State, Json};
use chrono::{Duration, Utc};
@@ -27,7 +27,7 @@ pub struct SessionResponse {
pub async fn register(
State(state): State<AppState>,
Json(req): Json<RegisterRequest>,
AppJson(req): AppJson<RegisterRequest>,
) -> ApiResult<Json<SessionResponse>> {
if req.username.trim().is_empty() || req.password.len() < 8 {
return Err(ApiError::BadRequest(
@@ -55,7 +55,7 @@ pub async fn register(
pub async fn login(
State(state): State<AppState>,
Json(req): Json<LoginRequest>,
AppJson(req): AppJson<LoginRequest>,
) -> ApiResult<Json<SessionResponse>> {
let user: Option<User> = sqlx::query_as("SELECT * FROM users WHERE username = $1")
.bind(&req.username)
+58 -7
View File
@@ -1,6 +1,6 @@
use crate::api::middleware::CurrentUser;
use crate::api::state::AppState;
use crate::error::ApiResult;
use crate::error::{ApiResult, AppJson};
use crate::models::Folder;
use axum::{extract::State, Json};
use serde::Deserialize;
@@ -14,18 +14,19 @@ pub async fn list(
State(state): State<AppState>,
user: CurrentUser,
) -> ApiResult<Json<Vec<Folder>>> {
let folders: Vec<Folder> =
sqlx::query_as("SELECT * FROM folders WHERE user_id = $1 ORDER BY name")
.bind(user.user_id)
.fetch_all(&state.pool)
.await?;
let folders: Vec<Folder> = sqlx::query_as(
"SELECT * FROM folders WHERE user_id = $1 ORDER BY role IS NULL, lower(name)",
)
.bind(user.user_id)
.fetch_all(&state.pool)
.await?;
Ok(Json(folders))
}
pub async fn create(
State(state): State<AppState>,
user: CurrentUser,
Json(req): Json<CreateFolderRequest>,
AppJson(req): AppJson<CreateFolderRequest>,
) -> ApiResult<Json<Folder>> {
let folder: Folder =
sqlx::query_as("INSERT INTO folders (user_id, name) VALUES ($1, $2) RETURNING *")
@@ -35,3 +36,53 @@ pub async fn create(
.await?;
Ok(Json(folder))
}
#[derive(Deserialize)]
pub struct RenameFolderRequest {
pub name: String,
}
pub async fn rename(
State(state): State<AppState>,
user: CurrentUser,
axum::extract::Path(id): axum::extract::Path<uuid::Uuid>,
AppJson(req): AppJson<RenameFolderRequest>,
) -> ApiResult<Json<Folder>> {
let name = req.name.trim();
if name.is_empty() || name.len() > 100 {
return Err(crate::error::ApiError::BadRequest(
"folder name must be 1–100 characters".into(),
));
}
let folder: Option<Folder> =
sqlx::query_as("UPDATE folders SET name = $3 WHERE id = $1 AND user_id = $2 RETURNING *")
.bind(id)
.bind(user.user_id)
.bind(name)
.fetch_optional(&state.pool)
.await?;
folder.map(Json).ok_or(crate::error::ApiError::NotFound)
}
/// Messages in a deleted folder go back to the inbox (FK ON DELETE SET
/// NULL) rather than disappearing. The Archive folder can be renamed but
/// not deleted, since archiving needs somewhere to put things.
pub async fn delete(
State(state): State<AppState>,
user: CurrentUser,
axum::extract::Path(id): axum::extract::Path<uuid::Uuid>,
) -> ApiResult<Json<serde_json::Value>> {
let deleted =
sqlx::query("DELETE FROM folders WHERE id = $1 AND user_id = $2 AND role IS NULL")
.bind(id)
.bind(user.user_id)
.execute(&state.pool)
.await?
.rows_affected();
if deleted == 0 {
return Err(crate::error::ApiError::BadRequest(
"folder not found, or it's the Archive folder, which can't be deleted".into(),
));
}
Ok(Json(serde_json::json!({ "ok": true })))
}
+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))
}
+4
View File
@@ -4,8 +4,12 @@ pub mod events;
pub mod folders;
pub mod messages;
pub mod middleware;
pub mod outbox;
pub mod router;
pub mod rules;
pub mod state;
pub mod tags;
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, AppJson};
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,
AppJson(req): AppJson<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>,
AppJson(req): AppJson<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"
))
}
+24 -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, rules, tags, threads};
use axum::routing::{delete, get, post, put};
use axum::Router;
use tower_http::cors::CorsLayer;
use tower_http::trace::TraceLayer;
@@ -10,11 +10,30 @@ 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/folders/:id",
put(folders::rename).delete(folders::delete),
)
.route("/api/tags", get(tags::list).post(tags::create))
.route("/api/tags/:id", put(tags::update).delete(tags::delete))
.route("/api/rules", get(rules::list).post(rules::create))
.route("/api/rules/reorder", post(rules::reorder))
.route("/api/rules/:id/run", post(rules::run))
.route("/api/rules/:id", put(rules::update).delete(rules::delete))
.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/threads/:id/actions", post(threads::act))
.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())
+214
View File
@@ -0,0 +1,214 @@
//! CRUD for rules. The engine itself lives in `crate::rules`; this only
//! validates and stores the structured JSON (server-architecture-spec.md
//! §3.5).
use crate::api::middleware::CurrentUser;
use crate::api::state::AppState;
use crate::error::{ApiError, ApiResult, AppJson};
use crate::rules::{self, Action, Conditions};
use axum::{
extract::{Path, State},
Json,
};
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use sqlx::types::Json as SqlJson;
use uuid::Uuid;
#[derive(Serialize, sqlx::FromRow)]
pub struct Rule {
pub id: Uuid,
pub name: String,
pub conditions: SqlJson<Conditions>,
pub actions: SqlJson<Vec<Action>>,
pub enabled: bool,
/// Skip lower-priority rules once this one matches.
pub stop_after_match: bool,
pub priority: i32,
pub created_at: DateTime<Utc>,
}
#[derive(Deserialize)]
pub struct RuleRequest {
pub name: String,
pub conditions: Conditions,
pub actions: Vec<Action>,
#[serde(default = "enabled_default")]
pub enabled: bool,
#[serde(default)]
pub stop_after_match: bool,
}
fn enabled_default() -> bool {
true
}
#[derive(Deserialize)]
pub struct ReorderRequest {
/// Every rule id, in the new priority order.
pub ids: Vec<Uuid>,
}
const RULE_COLUMNS: &str =
"id, name, conditions, actions, enabled, stop_after_match, priority, created_at";
async fn check(state: &AppState, user_id: Uuid, req: &RuleRequest) -> ApiResult<()> {
let name = req.name.trim();
if name.is_empty() || name.len() > 100 {
return Err(ApiError::BadRequest(
"rule name must be 1–100 characters".into(),
));
}
rules::validate(&req.conditions, &req.actions, true).map_err(ApiError::BadRequest)?;
rules::check_targets(&state.pool, user_id, &req.actions)
.await
.map_err(ApiError::BadRequest)
}
pub async fn list(State(state): State<AppState>, user: CurrentUser) -> ApiResult<Json<Vec<Rule>>> {
let rules = sqlx::query_as(&format!(
"SELECT {RULE_COLUMNS} FROM rules WHERE user_id = $1 ORDER BY priority, created_at"
))
.bind(user.user_id)
.fetch_all(&state.pool)
.await?;
Ok(Json(rules))
}
/// New rules go to the bottom of the list, so adding one never changes what
/// the existing ones do.
pub async fn create(
State(state): State<AppState>,
user: CurrentUser,
AppJson(req): AppJson<RuleRequest>,
) -> ApiResult<Json<Rule>> {
check(&state, user.user_id, &req).await?;
let rule = sqlx::query_as(&format!(
"INSERT INTO rules (user_id, name, conditions, actions, enabled, stop_after_match, priority) \
VALUES ($1, $2, $3, $4, $5, $6, \
COALESCE((SELECT MAX(priority) + 1 FROM rules WHERE user_id = $1), 0)) \
RETURNING {RULE_COLUMNS}"
))
.bind(user.user_id)
.bind(req.name.trim())
.bind(SqlJson(&req.conditions))
.bind(SqlJson(&req.actions))
.bind(req.enabled)
.bind(req.stop_after_match)
.fetch_one(&state.pool)
.await?;
Ok(Json(rule))
}
pub async fn update(
State(state): State<AppState>,
user: CurrentUser,
Path(id): Path<Uuid>,
AppJson(req): AppJson<RuleRequest>,
) -> ApiResult<Json<Rule>> {
check(&state, user.user_id, &req).await?;
let rule: Option<Rule> = sqlx::query_as(&format!(
"UPDATE rules SET name = $3, conditions = $4, actions = $5, enabled = $6, \
stop_after_match = $7 \
WHERE id = $1 AND user_id = $2 RETURNING {RULE_COLUMNS}"
))
.bind(id)
.bind(user.user_id)
.bind(req.name.trim())
.bind(SqlJson(&req.conditions))
.bind(SqlJson(&req.actions))
.bind(req.enabled)
.bind(req.stop_after_match)
.fetch_optional(&state.pool)
.await?;
rule.map(Json).ok_or(ApiError::NotFound)
}
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 rules WHERE id = $1 AND user_id = $2")
.bind(id)
.bind(user.user_id)
.execute(&state.pool)
.await?
.rows_affected();
if deleted == 0 {
return Err(ApiError::NotFound);
}
Ok(Json(serde_json::json!({ "ok": true })))
}
/// Takes the complete new order rather than "move rule X up", so the
/// client can't leave two rules at the same priority and make evaluation
/// order depend on insertion time.
pub async fn reorder(
State(state): State<AppState>,
user: CurrentUser,
AppJson(req): AppJson<ReorderRequest>,
) -> ApiResult<Json<Vec<Rule>>> {
let mut tx = state.pool.begin().await?;
let mut existing: Vec<Uuid> =
sqlx::query_scalar("SELECT id FROM rules WHERE user_id = $1 FOR UPDATE")
.bind(user.user_id)
.fetch_all(&mut *tx)
.await?;
let mut given = req.ids.clone();
existing.sort();
given.sort();
if existing != given {
return Err(ApiError::BadRequest(
"reorder needs every one of your rule ids exactly once".into(),
));
}
sqlx::query(
"UPDATE rules SET priority = o.ord - 1 \
FROM unnest($1::uuid[]) WITH ORDINALITY AS o(id, ord) \
WHERE rules.id = o.id AND rules.user_id = $2",
)
.bind(&req.ids)
.bind(user.user_id)
.execute(&mut *tx)
.await?;
tx.commit().await?;
list(State(state), user).await
}
#[derive(Serialize)]
pub struct RunResponse {
pub scanned: usize,
pub matched: usize,
}
/// "Run now": applies one rule to existing received mail. Works on disabled
/// rules too, so a rule can be tried out before it's switched on for new
/// mail. Stored as-is is what runs — unsaved edits in the editor don't.
pub async fn run(
State(state): State<AppState>,
user: CurrentUser,
Path(id): Path<Uuid>,
) -> ApiResult<Json<RunResponse>> {
let stored: rules::StoredRule = sqlx::query_as(
"SELECT id, conditions, actions, stop_after_match FROM rules WHERE id = $1 AND user_id = $2",
)
.bind(id)
.bind(user.user_id)
.fetch_optional(&state.pool)
.await?
.ok_or(ApiError::NotFound)?;
let rule = rules::CompiledRule::compile(stored.id, stored.conditions.0, stored.actions.0)
.map_err(ApiError::BadRequest)?;
let summary = rules::run_on_existing(&state.pool, &state.blobs, user.user_id, &rule).await?;
tracing::info!(rule_id = %id, scanned = summary.scanned, matched = summary.matched, "ran rule on existing mail");
Ok(Json(RunResponse {
scanned: summary.scanned,
matched: summary.matched,
}))
}
+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 @@
use crate::api::middleware::CurrentUser;
use crate::api::state::AppState;
use crate::error::{ApiError, ApiResult, AppJson};
use crate::models::tag::Tag;
use axum::{
extract::{Path, State},
Json,
};
use serde::Deserialize;
use uuid::Uuid;
#[derive(Deserialize)]
pub struct TagRequest {
pub name: String,
pub color: Option<String>,
}
/// Colours are rendered into the UI's styles, so only `#rrggbb` is
/// accepted — nothing that could smuggle other CSS in. The database
/// enforces the same with a CHECK constraint.
fn validate(req: &TagRequest) -> ApiResult<(String, Option<String>)> {
let name = req.name.trim();
if name.is_empty() || name.len() > 64 {
return Err(ApiError::BadRequest(
"tag name must be 1–64 characters".into(),
));
}
let color = match req.color.as_deref().map(str::trim) {
None | Some("") => None,
Some(c)
if c.len() == 7
&& c.starts_with('#')
&& c[1..].chars().all(|ch| ch.is_ascii_hexdigit()) =>
{
Some(c.to_lowercase())
}
Some(c) => {
return Err(ApiError::BadRequest(format!(
"color must look like #rrggbb, got {c:?}"
)))
}
};
Ok((name.to_string(), color))
}
fn conflict(e: sqlx::Error) -> ApiError {
match e {
sqlx::Error::Database(db) if db.is_unique_violation() => {
ApiError::BadRequest("a tag with that name already exists".into())
}
other => ApiError::Sqlx(other),
}
}
pub async fn list(State(state): State<AppState>, user: CurrentUser) -> ApiResult<Json<Vec<Tag>>> {
let tags = sqlx::query_as("SELECT * FROM tags WHERE user_id = $1 ORDER BY lower(name)")
.bind(user.user_id)
.fetch_all(&state.pool)
.await?;
Ok(Json(tags))
}
pub async fn create(
State(state): State<AppState>,
user: CurrentUser,
AppJson(req): AppJson<TagRequest>,
) -> ApiResult<Json<Tag>> {
let (name, color) = validate(&req)?;
let tag =
sqlx::query_as("INSERT INTO tags (user_id, name, color) VALUES ($1, $2, $3) RETURNING *")
.bind(user.user_id)
.bind(name)
.bind(color)
.fetch_one(&state.pool)
.await
.map_err(conflict)?;
Ok(Json(tag))
}
pub async fn update(
State(state): State<AppState>,
user: CurrentUser,
Path(id): Path<Uuid>,
AppJson(req): AppJson<TagRequest>,
) -> ApiResult<Json<Tag>> {
let (name, color) = validate(&req)?;
let tag: Option<Tag> = sqlx::query_as(
"UPDATE tags SET name = $3, color = $4 WHERE id = $1 AND user_id = $2 RETURNING *",
)
.bind(id)
.bind(user.user_id)
.bind(name)
.bind(color)
.fetch_optional(&state.pool)
.await
.map_err(conflict)?;
tag.map(Json).ok_or(ApiError::NotFound)
}
/// Removes the tag from every message (cascade). Rules still naming it
/// become no-ops for that action rather than failing.
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 tags WHERE id = $1 AND user_id = $2")
.bind(id)
.bind(user.user_id)
.execute(&state.pool)
.await?
.rows_affected();
if deleted == 0 {
return Err(ApiError::NotFound);
}
Ok(Json(serde_json::json!({ "ok": true })))
}
+234
View File
@@ -0,0 +1,234 @@
//! Thread-grouped listing — one row per conversation, which is how both
//! clients render a mailbox — plus actions on a whole thread.
//!
//! Grouping has to happen 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.
//!
//! A view selects which threads appear (a thread is in the inbox if *any*
//! of its messages is), but each row summarises the whole conversation. So
//! a reply arriving in an archived thread brings the thread back into the
//! inbox, while the row still shows every message in it.
//!
//! 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::{ApiError, ApiResult, AppJson};
use crate::rules::{self, Action};
use axum::{
extract::{Path, Query, State},
Json,
};
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use uuid::Uuid;
#[derive(Deserialize, Default, Clone, Copy, PartialEq)]
#[serde(rename_all = "snake_case")]
pub enum View {
/// Received mail not filed into any folder.
#[default]
Inbox,
All,
Sent,
Trash,
Folder,
Tag,
}
impl View {
fn as_str(self) -> &'static str {
match self {
View::Inbox => "inbox",
View::All => "all",
View::Sent => "sent",
View::Trash => "trash",
View::Folder => "folder",
View::Tag => "tag",
}
}
}
#[derive(Deserialize)]
pub struct ListThreadsQuery {
#[serde(default)]
pub view: View,
pub folder_id: Option<Uuid>,
pub tag_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,
pub tag_ids: Vec<Uuid>,
/// In Trash: when the earliest-trashed message in the thread is purged
/// for good. None elsewhere, or when retention is disabled.
pub purges_at: Option<DateTime<Utc>>,
}
#[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);
match q.view {
View::Folder if q.folder_id.is_none() => {
return Err(ApiError::BadRequest("view=folder needs folder_id".into()))
}
View::Tag if q.tag_id.is_none() => {
return Err(ApiError::BadRequest("view=tag needs tag_id".into()))
}
_ => {}
}
// Deleted messages are left out of every summary except Trash's, so a
// thread with one message deleted by a rule doesn't count it.
let threads: Vec<ThreadSummary> = sqlx::query_as(
r#"
WITH mine AS (
SELECT m.* FROM messages m
JOIN accounts a ON a.id = m.account_id
WHERE a.user_id = $1
),
selected AS (
SELECT DISTINCT thread_id FROM mine v
WHERE CASE $2
WHEN 'inbox' THEN v.deleted_at IS NULL AND v.folder_id IS NULL AND v.source = 'imap'
WHEN 'all' THEN v.deleted_at IS NULL
WHEN 'sent' THEN v.deleted_at IS NULL AND v.source = 'sent'
WHEN 'trash' THEN v.deleted_at IS NOT NULL
WHEN 'folder' THEN v.deleted_at IS NULL AND v.folder_id = $3
WHEN 'tag' THEN v.deleted_at IS NULL AND EXISTS (
SELECT 1 FROM message_tags mt WHERE mt.message_id = v.id AND mt.tag_id = $4)
END
)
SELECT
m.thread_id,
-- The root's subject when we have the root (a message that
-- replies to nothing), not merely the earliest-dated message:
-- replies can carry earlier Date headers than their parent, and
-- Date has one-second resolution, so ties are common. Arrival
-- order breaks the remaining ties deterministically.
(ARRAY_AGG(m.subject ORDER BY
(m.in_reply_to IS NOT NULL OR cardinality(m.references_) > 0),
m.sent_at ASC NULLS LAST,
m.created_at ASC))[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,
ARRAY(
SELECT DISTINCT mt.tag_id FROM message_tags mt
JOIN mine m2 ON m2.id = mt.message_id
WHERE m2.thread_id = m.thread_id AND m2.deleted_at IS NULL
) AS tag_ids,
CASE WHEN $2 = 'trash' AND $7 > 0
THEN MIN(m.deleted_at) + make_interval(days => $7) END AS purges_at
FROM mine m
JOIN selected USING (thread_id)
WHERE ($2 = 'trash') = (m.deleted_at IS NOT NULL)
GROUP BY m.thread_id
HAVING MAX(m.sent_at) < $5
ORDER BY last_message_at DESC
LIMIT $6
"#,
)
.bind(user.user_id)
.bind(q.view.as_str())
.bind(q.folder_id)
.bind(q.tag_id)
.bind(before)
.bind(limit)
.bind(state.config.trash_retention_days as i32)
.fetch_all(&state.pool)
.await?;
let next_cursor = threads.last().and_then(|t| t.last_message_at);
Ok(Json(ListThreadsResponse {
threads,
next_cursor,
}))
}
#[derive(Deserialize)]
pub struct ThreadActionsRequest {
pub actions: Vec<Action>,
}
/// Applies actions to every message in a thread — the same action format and
/// code as rules, so "archive this conversation" and "a rule that
/// archives" can't drift apart.
pub async fn act(
State(state): State<AppState>,
user: CurrentUser,
Path(thread_id): Path<Uuid>,
AppJson(req): AppJson<ThreadActionsRequest>,
) -> ApiResult<Json<serde_json::Value>> {
let no_conditions = rules::Conditions {
match_: rules::Match::All,
tests: vec![],
};
rules::validate(&no_conditions, &req.actions, false).map_err(ApiError::BadRequest)?;
rules::check_targets(&state.pool, user.user_id, &req.actions)
.await
.map_err(ApiError::BadRequest)?;
let ids: Vec<Uuid> = sqlx::query_scalar(
"SELECT m.id FROM messages m JOIN accounts a ON a.id = m.account_id \
WHERE m.thread_id = $1 AND a.user_id = $2",
)
.bind(thread_id)
.bind(user.user_id)
.fetch_all(&state.pool)
.await?;
if ids.is_empty() {
return Err(ApiError::NotFound);
}
let mut tx = state.pool.begin().await?;
rules::apply_actions(&mut tx, user.user_id, &ids, &req.actions).await?;
tx.commit().await?;
Ok(Json(serde_json::json!({ "messages": ids.len() })))
}
/// 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<AppState>,
user: CurrentUser,
thread_id: Path<Uuid>,
) -> ApiResult<Json<serde_json::Value>> {
act(
state,
user,
thread_id,
AppJson(ThreadActionsRequest {
actions: vec![Action::MarkRead],
}),
)
.await
}
+12
View File
@@ -10,6 +10,8 @@ pub struct Config {
/// Directory raw MIME blobs and attachments are stored under (§3.2).
pub blob_storage_dir: std::path::PathBuf,
pub session_ttl_hours: i64,
/// Days mail stays in Trash before it's purged for good. 0 disables.
pub trash_retention_days: u32,
}
impl Config {
@@ -42,12 +44,22 @@ impl Config {
.and_then(|v| v.parse().ok())
.unwrap_or(24 * 30);
let trash_retention_days = std::env::var("TRASH_RETENTION_DAYS")
.ok()
.map(|v| {
v.parse()
.context("TRASH_RETENTION_DAYS must be a whole number of days")
})
.transpose()?
.unwrap_or(30);
Ok(Self {
database_url,
bind_addr,
credential_key,
blob_storage_dir,
session_ttl_hours,
trash_retention_days,
})
}
}
+14
View File
@@ -45,3 +45,17 @@ impl IntoResponse for ApiError {
}
pub type ApiResult<T> = Result<T, ApiError>;
/// JSON body extractor whose failures use the API's `{"error": …}` shape.
/// Axum's own `Json` rejects malformed or mistyped bodies with a plain-text
/// 422, which clients can't show properly — and its message is exactly the
/// useful part ("unknown variant `stop`, expected one of …").
#[derive(axum::extract::FromRequest)]
#[from_request(via(axum::Json), rejection(ApiError))]
pub struct AppJson<T>(pub T);
impl From<axum::extract::rejection::JsonRejection> for ApiError {
fn from(rejection: axum::extract::rejection::JsonRejection) -> Self {
ApiError::BadRequest(rejection.body_text())
}
}
+49 -5
View File
@@ -126,6 +126,7 @@ impl AccountSyncer {
let server_uidvalidity = mailbox.uid_validity.map(|v| v as i64);
self.reconcile_uidvalidity(server_uidvalidity).await?;
crate::threading::backfill_if_needed(&self.pool, self.account.id).await?;
// Catch up on anything new, then keep going until told to stop.
// `Session::idle()` consumes the session and hands back a `Handle`;
@@ -164,12 +165,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 +244,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 +287,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)
@@ -368,6 +388,30 @@ impl AccountSyncer {
.await?;
}
// Threading and rules need the full headers (References isn't in
// ENVELOPE), so they run here rather than at header ingest — the
// message may be visible for the moment between the two.
crate::threading::assign(
&mut tx,
&crate::threading::ThreadInput {
account_id: self.account.id,
row_id: message_row_id,
message_id: parsed.message_id.as_deref(),
in_reply_to: parsed.in_reply_to.as_deref(),
references: &parsed.references,
subject: parsed.subject.as_deref(),
},
)
.await?;
crate::rules::apply_rules(
&mut tx,
self.account.user_id,
message_row_id,
&crate::rules::Facts::from_parsed(&parsed),
)
.await?;
tx.commit().await?;
Ok(())
}
+54
View File
@@ -47,6 +47,19 @@ pub fn parse_raw_message(raw: &[u8]) -> anyhow::Result<ParsedMessage> {
})
.collect();
let raw_bytes = message.raw_message();
let headers = message
.headers()
.iter()
.filter_map(|h| {
let value = raw_bytes.get(h.offset_start as usize..h.offset_end as usize)?;
Some((
h.name.as_str().to_lowercase(),
unfold(&String::from_utf8_lossy(value)),
))
})
.collect();
Ok(ParsedMessage {
message_id,
in_reply_to,
@@ -60,10 +73,18 @@ pub fn parse_raw_message(raw: &[u8]) -> anyhow::Result<ParsedMessage> {
text_body,
html_body,
attachments,
headers,
raw: raw.to_vec(),
})
}
/// Joins a folded header (continuation lines start with whitespace) back
/// into one line, so a rule doesn't have to account for where a sender's
/// mailer chose to wrap it.
fn unfold(value: &str) -> String {
value.split_whitespace().collect::<Vec<_>>().join(" ")
}
fn first_address(addr: &Address) -> Option<(Option<String>, Option<String>)> {
addr.first().map(|a| {
(
@@ -78,3 +99,36 @@ fn all_addresses(addr: &Address) -> Vec<String> {
.filter_map(|a| a.address().map(|s| s.to_string()))
.collect()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn exposes_unfolded_raw_headers_including_repeats() {
let raw = b"From: Bob <bob@example.com>\r\n\
Received: from a\r\n\
Received: from b\r\n\
List-Id: Weekly digest\r\n <weekly.lists.example.com>\r\n\
X-Spam-Score: 5.3\r\n\
Subject: hi\r\n\
\r\n\
body\r\n";
let p = parse_raw_message(raw).unwrap();
let get = |n: &str| {
p.headers
.iter()
.filter(|(k, _)| k == n)
.map(|(_, v)| v.as_str())
.collect::<Vec<_>>()
};
assert_eq!(
get("list-id"),
vec!["Weekly digest <weekly.lists.example.com>"]
);
assert_eq!(get("received"), vec!["from a", "from b"]);
assert_eq!(get("x-spam-score"), vec!["5.3"]);
assert_eq!(get("from"), vec!["Bob <bob@example.com>"]);
}
}
+4
View File
@@ -6,4 +6,8 @@ pub mod db;
pub mod error;
pub mod imap_sync;
pub mod models;
pub mod retention;
pub mod rules;
pub mod smtp;
pub mod storage;
pub mod threading;
+15
View File
@@ -25,12 +25,27 @@ 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()));
tokio::spawn(tern_server::retention::run(
pool.clone(),
blobs.clone(),
config.trash_retention_days,
));
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,
}
}
+2
View File
@@ -8,4 +8,6 @@ pub struct Folder {
pub user_id: Uuid,
pub name: String,
pub created_at: DateTime<Utc>,
/// 'archive' for the system Archive folder, None for the user's own.
pub role: Option<String>,
}
+9 -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,7 +23,11 @@ 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>,
/// Set when moved to Trash.
pub deleted_at: Option<DateTime<Utc>>,
}
#[derive(Debug, Clone, sqlx::FromRow, Serialize)]
@@ -47,6 +52,9 @@ pub struct ParsedMessage {
pub text_body: Option<String>,
pub html_body: Option<String>,
pub attachments: Vec<ParsedAttachment>,
/// Every header as (lowercased name, unfolded raw value), in order —
/// what rules match against. Repeats (Received, …) are kept.
pub headers: Vec<(String, String)>,
pub raw: Vec<u8>,
}
+2
View File
@@ -1,6 +1,8 @@
pub mod account;
pub mod folder;
pub mod message;
pub mod outbox;
pub mod tag;
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>>,
}
+10
View File
@@ -0,0 +1,10 @@
use serde::Serialize;
use uuid::Uuid;
#[derive(Debug, Clone, sqlx::FromRow, Serialize)]
pub struct Tag {
pub id: Uuid,
pub user_id: Uuid,
pub name: String,
pub color: Option<String>,
}
+120
View File
@@ -0,0 +1,120 @@
//! Permanently removes mail that has sat in Trash past the retention period.
//!
//! Stored files are content-addressed and shared: two identical messages or
//! attachments point at the same file. So a file is only removed once no
//! remaining row references it — and not if it was written or reused within
//! the last hour, because ingest writes a file *before* inserting the row
//! that references it. Without that grace period, a purge landing between
//! those two steps for an identical message would delete a file the new row
//! is about to depend on.
//!
//! One consequence of one-way sync: purged mail never comes back, since the
//! sync engine only fetches UIDs above the last one seen. A UIDVALIDITY
//! reset is the exception — that re-syncs the whole INBOX.
use crate::storage::BlobStore;
use sqlx::PgPool;
use std::time::Duration;
use uuid::Uuid;
const INTERVAL: Duration = Duration::from_secs(60 * 60);
const BATCH: i64 = 500;
const BLOB_GRACE: Duration = Duration::from_secs(60 * 60);
pub async fn run(pool: PgPool, blobs: BlobStore, retention_days: u32) {
if retention_days == 0 {
tracing::info!("trash retention disabled (TRASH_RETENTION_DAYS=0)");
return;
}
loop {
match purge(&pool, &blobs, retention_days).await {
Ok(0) => {}
Ok(n) => tracing::info!(
purged = n,
retention_days,
"purged expired messages from trash"
),
Err(e) => tracing::error!(error = %e, "trash purge failed"),
}
tokio::time::sleep(INTERVAL).await;
}
}
pub async fn purge(pool: &PgPool, blobs: &BlobStore, retention_days: u32) -> anyhow::Result<usize> {
let mut total = 0;
loop {
let mut tx = pool.begin().await?;
let batch: Vec<(Uuid, Option<String>)> = sqlx::query_as(
"SELECT id, raw_blob_ref FROM messages \
WHERE deleted_at < now() - make_interval(days => $1) \
ORDER BY deleted_at LIMIT $2 FOR UPDATE SKIP LOCKED",
)
.bind(retention_days as i32)
.bind(BATCH)
.fetch_all(&mut *tx)
.await?;
if batch.is_empty() {
break;
}
let ids: Vec<Uuid> = batch.iter().map(|(id, _)| *id).collect();
let mut refs: Vec<String> = batch.into_iter().filter_map(|(_, r)| r).collect();
let attachment_refs: Vec<String> =
sqlx::query_scalar("SELECT blob_ref FROM attachments WHERE message_id = ANY($1)")
.bind(&ids)
.fetch_all(&mut *tx)
.await?;
refs.extend(attachment_refs);
// Bodies, attachments and tags cascade; an outbox row pointing at a
// purged sent message keeps its record with the link set to NULL.
sqlx::query("DELETE FROM messages WHERE id = ANY($1)")
.bind(&ids)
.execute(&mut *tx)
.await?;
tx.commit().await?;
total += ids.len();
refs.sort();
refs.dedup();
remove_orphaned_blobs(pool, blobs, &refs).await?;
}
Ok(total)
}
async fn remove_orphaned_blobs(
pool: &PgPool,
blobs: &BlobStore,
refs: &[String],
) -> anyhow::Result<()> {
for r in refs {
let still_used: bool = sqlx::query_scalar(
"SELECT EXISTS (SELECT 1 FROM messages WHERE raw_blob_ref = $1) \
OR EXISTS (SELECT 1 FROM attachments WHERE blob_ref = $1)",
)
.bind(r)
.fetch_one(pool)
.await?;
if still_used {
continue;
}
let path = blobs.resolve(r);
let recent = tokio::fs::metadata(&path)
.await
.ok()
.and_then(|m| m.modified().ok())
.and_then(|t| t.elapsed().ok())
.is_some_and(|age| age < BLOB_GRACE);
if recent {
continue;
}
match tokio::fs::remove_file(&path).await {
Ok(()) => {}
Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
Err(e) => {
tracing::warn!(path = %path.display(), error = %e, "couldn't remove orphaned blob")
}
}
}
Ok(())
}
+822
View File
@@ -0,0 +1,822 @@
//! Rule engine (server-architecture-spec.md §3.5).
//!
//! Rules are structured JSON — a condition list plus an action list — so the
//! webapp can render and edit them without a parser. Conditions are one
//! level deep (`all` / `any` of tests), which is exactly what the editor can
//! show; a deeper tree would make rules the API could create but the UI
//! couldn't edit.
//!
//! Every enabled rule that matches applies, in priority order, until one
//! marked `stop_after_match`. That's the Sieve/Outlook model, rather than
//! first-match-wins, because it lets a general rule ("tag anything from a
//! mailing list") and a specific one ("archive this list") both apply.
//!
//! The same `Action` type is used for manual actions from the UI, so
//! "archive this thread" and "a rule that archives" run the same code.
use crate::models::message::ParsedMessage;
use regex::{Regex, RegexBuilder};
use serde::{Deserialize, Serialize};
use sqlx::{PgPool, Postgres, Transaction};
use std::sync::LazyLock;
use uuid::Uuid;
/// Patterns are user-written and evaluated against every incoming message.
/// The regex crate matches in linear time, so no pattern can hang ingestion
/// (no catastrophic backtracking); the size cap bounds compile cost too.
const REGEX_SIZE_LIMIT: usize = 256 * 1024;
const MAX_TESTS: usize = 20;
const MAX_ACTIONS: usize = 10;
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "snake_case")]
pub enum Match {
All,
Any,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "snake_case")]
pub enum Field {
From,
To,
Cc,
/// To and Cc together — "was this sent to the list address".
Recipients,
Subject,
Body,
/// Any header by name, e.g. List-Id, or the PMG spam headers phase 6
/// will use.
Header,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "snake_case")]
pub enum Op {
Contains,
Equals,
/// Regular expression, case-insensitive.
Matches,
Exists,
/// Numeric, comparing the first number in the value — so both
/// "5.3" and "Yes, score=5.3" work for spam-score headers.
GreaterThan,
LessThan,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Test {
pub field: Field,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub header: Option<String>,
pub op: Op,
#[serde(default)]
pub value: String,
#[serde(default)]
pub negate: bool,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Conditions {
#[serde(rename = "match")]
pub match_: Match,
pub tests: Vec<Test>,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum Action {
Tag {
tag_id: Uuid,
},
Untag {
tag_id: Uuid,
},
/// `None` moves back to the inbox.
Move {
folder_id: Option<Uuid>,
},
Archive,
MarkRead,
MarkUnread,
/// Soft delete — to Trash, restorable.
Delete,
Restore,
}
impl Action {
fn allowed_in_rules(&self) -> bool {
matches!(
self,
Action::Tag { .. }
| Action::Move { .. }
| Action::Archive
| Action::MarkRead
| Action::Delete
)
}
}
/// What a rule can see about a message.
pub struct Facts {
pub from: String,
pub to: String,
pub cc: String,
pub subject: String,
pub body: String,
/// Lowercased names; a header can repeat (Received, …).
pub headers: Vec<(String, String)>,
}
impl Facts {
pub fn from_parsed(p: &ParsedMessage) -> Self {
let from = format_from(p.from_name.as_deref(), p.from_addr.as_deref());
Facts {
from,
to: p.to_addrs.join(", "),
cc: p.cc_addrs.join(", "),
subject: p.subject.clone().unwrap_or_default(),
body: p
.text_body
.clone()
.or_else(|| p.html_body.clone())
.unwrap_or_default(),
headers: p.headers.clone(),
}
}
}
/// A validated rule, with its patterns compiled once.
pub struct CompiledRule {
pub id: Uuid,
pub conditions: Conditions,
pub actions: Vec<Action>,
patterns: Vec<Option<Regex>>,
}
static NUMBER: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"-?\d+(?:\.\d+)?").unwrap());
fn first_number(s: &str) -> Option<f64> {
NUMBER.find(s).and_then(|m| m.as_str().parse().ok())
}
fn compile_pattern(pattern: &str) -> Result<Regex, String> {
RegexBuilder::new(pattern)
.case_insensitive(true)
.size_limit(REGEX_SIZE_LIMIT)
.build()
.map_err(|e| format!("invalid pattern {pattern:?}: {e}"))
}
/// Structural checks that don't need the database. Ownership of any
/// referenced tag or folder is checked separately by the API.
pub fn validate(conditions: &Conditions, actions: &[Action], for_rule: bool) -> Result<(), String> {
if for_rule {
if conditions.tests.is_empty() {
return Err("a rule needs at least one condition".into());
}
if conditions.tests.len() > MAX_TESTS {
return Err(format!("at most {MAX_TESTS} conditions per rule"));
}
}
for t in &conditions.tests {
if t.field == Field::Header && t.header.as_deref().map(str::trim).unwrap_or("").is_empty() {
return Err("a header condition needs a header name".into());
}
match t.op {
Op::Matches => {
compile_pattern(&t.value)?;
}
Op::GreaterThan | Op::LessThan => {
if t.value.trim().parse::<f64>().is_err() {
return Err(format!("{:?} needs a number, got {:?}", t.op, t.value));
}
}
Op::Contains | Op::Equals => {
if t.value.is_empty() {
return Err("contains / equals needs a value".into());
}
}
Op::Exists => {}
}
}
if actions.is_empty() {
return Err("at least one action is required".into());
}
if actions.len() > MAX_ACTIONS {
return Err(format!("at most {MAX_ACTIONS} actions"));
}
if for_rule {
if let Some(a) = actions.iter().find(|a| !a.allowed_in_rules()) {
return Err(format!("{a:?} isn't available as a rule action"));
}
}
Ok(())
}
impl CompiledRule {
pub fn compile(id: Uuid, conditions: Conditions, actions: Vec<Action>) -> Result<Self, String> {
validate(&conditions, &actions, true)?;
let patterns = conditions
.tests
.iter()
.map(|t| {
(t.op == Op::Matches)
.then(|| compile_pattern(&t.value))
.transpose()
})
.collect::<Result<_, _>>()?;
Ok(Self {
id,
conditions,
actions,
patterns,
})
}
/// Header tests need the raw message re-parsed; everything else is in
/// stored columns. Lets a run over existing mail skip parsing when the
/// rule doesn't look at headers.
pub fn needs_headers(&self) -> bool {
self.conditions
.tests
.iter()
.any(|t| t.field == Field::Header)
}
pub fn matches(&self, facts: &Facts) -> bool {
let mut results = self
.conditions
.tests
.iter()
.zip(&self.patterns)
.map(|(t, re)| eval_test(t, re.as_ref(), facts) != t.negate);
match self.conditions.match_ {
Match::All => results.all(|r| r),
Match::Any => results.any(|r| r),
}
}
}
fn eval_test(t: &Test, re: Option<&Regex>, facts: &Facts) -> bool {
let recipients;
let values: Vec<&str> = match t.field {
Field::From => vec![&facts.from],
Field::To => vec![&facts.to],
Field::Cc => vec![&facts.cc],
Field::Recipients => {
recipients = format!("{}, {}", facts.to, facts.cc);
vec![&recipients]
}
Field::Subject => vec![&facts.subject],
Field::Body => vec![&facts.body],
Field::Header => {
let name = t.header.as_deref().unwrap_or("").trim().to_lowercase();
facts
.headers
.iter()
.filter(|(n, _)| *n == name)
.map(|(_, v)| v.as_str())
.collect()
}
};
let needle = t.value.to_lowercase();
// Any occurrence matching is enough (a header can repeat).
values.iter().any(|v| match t.op {
Op::Exists => !v.trim().is_empty(),
Op::Contains => v.to_lowercase().contains(&needle),
Op::Equals => v.trim().eq_ignore_ascii_case(t.value.trim()),
Op::Matches => re.is_some_and(|re| re.is_match(v)),
Op::GreaterThan => cmp_number(v, &t.value).is_some_and(|(a, b)| a > b),
Op::LessThan => cmp_number(v, &t.value).is_some_and(|(a, b)| a < b),
})
}
fn cmp_number(value: &str, threshold: &str) -> Option<(f64, f64)> {
Some((first_number(value)?, threshold.trim().parse().ok()?))
}
/// Runs the user's enabled rules against a freshly ingested message, inside
/// the ingest transaction. A rule that no longer compiles (e.g. written
/// before a validation change) is skipped and logged rather than blocking
/// mail.
pub async fn apply_rules(
tx: &mut Transaction<'_, Postgres>,
user_id: Uuid,
message_row_id: Uuid,
facts: &Facts,
) -> sqlx::Result<()> {
let rows: Vec<StoredRule> = sqlx::query_as(
"SELECT id, conditions, actions, stop_after_match FROM rules \
WHERE user_id = $1 AND enabled ORDER BY priority, created_at",
)
.bind(user_id)
.fetch_all(&mut **tx)
.await?;
for StoredRule {
id,
conditions,
actions,
stop_after_match,
} in rows
{
let rule = match CompiledRule::compile(id, conditions.0, actions.0) {
Ok(r) => r,
Err(e) => {
tracing::warn!(rule_id = %id, error = %e, "skipping invalid rule");
continue;
}
};
if !rule.matches(facts) {
continue;
}
tracing::debug!(rule_id = %id, message = %message_row_id, "rule matched");
apply_actions(tx, user_id, &[message_row_id], &rule.actions).await?;
if stop_after_match {
break;
}
}
Ok(())
}
#[derive(sqlx::FromRow)]
struct ExistingMessage {
id: Uuid,
from_addr: Option<String>,
from_name: Option<String>,
to_addrs: Vec<String>,
cc_addrs: Vec<String>,
subject: Option<String>,
raw_blob_ref: Option<String>,
text_body: Option<String>,
html_body: Option<String>,
}
pub struct RunSummary {
pub scanned: usize,
pub matched: usize,
}
const RUN_PAGE: i64 = 500;
/// Applies one rule to the user's existing received mail — "run now".
///
/// Covers everything not in Trash, including mail already filed away, since
/// that's what "apply this rule to what I already have" means. Sent mail is
/// left alone: rules are for incoming mail. Messages whose body hasn't been
/// fetched yet are skipped; they'll meet the rule on ingest anyway.
///
/// Walks by id (keyset, not offset) in pages, one transaction per page, so
/// a large mailbox doesn't hold one enormous transaction. Stored raw
/// messages are only re-read and re-parsed when the rule has a header test.
pub async fn run_on_existing(
pool: &PgPool,
blobs: &crate::storage::BlobStore,
user_id: Uuid,
rule: &CompiledRule,
) -> sqlx::Result<RunSummary> {
let mut after = Uuid::nil();
let mut summary = RunSummary {
scanned: 0,
matched: 0,
};
let needs_headers = rule.needs_headers();
loop {
let page: Vec<ExistingMessage> = sqlx::query_as(
"SELECT m.id, m.from_addr, m.from_name, m.to_addrs, m.cc_addrs, m.subject, \
m.raw_blob_ref, b.text_body, b.html_body \
FROM messages m \
JOIN accounts a ON a.id = m.account_id \
LEFT JOIN bodies b ON b.message_id = m.id \
WHERE a.user_id = $1 AND m.source = 'imap' AND m.deleted_at IS NULL \
AND m.body_fetched AND m.id > $2 \
ORDER BY m.id LIMIT $3",
)
.bind(user_id)
.bind(after)
.bind(RUN_PAGE)
.fetch_all(pool)
.await?;
let Some(last) = page.last() else { break };
after = last.id;
summary.scanned += page.len();
let mut matched = Vec::new();
for m in &page {
let headers = match (&m.raw_blob_ref, needs_headers) {
(Some(r), true) => match blobs.read(r).await {
Ok(raw) => crate::imap_sync::parse::parse_raw_message(&raw)
.map(|p| p.headers)
.unwrap_or_default(),
Err(e) => {
tracing::warn!(message = %m.id, error = %e, "raw message unreadable; header tests won't match");
Vec::new()
}
},
_ => Vec::new(),
};
let facts = Facts {
from: format_from(m.from_name.as_deref(), m.from_addr.as_deref()),
to: m.to_addrs.join(", "),
cc: m.cc_addrs.join(", "),
subject: m.subject.clone().unwrap_or_default(),
body: m
.text_body
.clone()
.or_else(|| m.html_body.clone())
.unwrap_or_default(),
headers,
};
if rule.matches(&facts) {
matched.push(m.id);
}
}
if !matched.is_empty() {
let mut tx = pool.begin().await?;
apply_actions(&mut tx, user_id, &matched, &rule.actions).await?;
tx.commit().await?;
summary.matched += matched.len();
}
}
Ok(summary)
}
fn format_from(name: Option<&str>, addr: Option<&str>) -> String {
match (name, addr) {
(Some(n), Some(a)) => format!("{n} <{a}>"),
(None, Some(a)) => a.to_string(),
(Some(n), None) => n.to_string(),
(None, None) => String::new(),
}
}
#[derive(sqlx::FromRow)]
pub struct StoredRule {
pub id: Uuid,
pub conditions: sqlx::types::Json<Conditions>,
pub actions: sqlx::types::Json<Vec<Action>>,
pub stop_after_match: bool,
}
/// Applies actions to messages the caller has already scoped to `user_id`.
/// Tag and folder targets are re-checked against the user here too, so a
/// rule referencing a since-deleted tag is a no-op rather than an error.
pub async fn apply_actions(
tx: &mut Transaction<'_, Postgres>,
user_id: Uuid,
message_ids: &[Uuid],
actions: &[Action],
) -> sqlx::Result<()> {
for action in actions {
match action {
Action::Tag { tag_id } => {
sqlx::query(
"INSERT INTO message_tags (message_id, tag_id) \
SELECT m, $2 FROM unnest($1::uuid[]) AS m \
WHERE EXISTS (SELECT 1 FROM tags WHERE id = $2 AND user_id = $3) \
ON CONFLICT DO NOTHING",
)
.bind(message_ids)
.bind(tag_id)
.bind(user_id)
.execute(&mut **tx)
.await?;
}
Action::Untag { tag_id } => {
sqlx::query("DELETE FROM message_tags WHERE message_id = ANY($1) AND tag_id = $2")
.bind(message_ids)
.bind(tag_id)
.execute(&mut **tx)
.await?;
}
Action::Move { folder_id } => {
sqlx::query(
"UPDATE messages SET folder_id = $2 WHERE id = ANY($1) \
AND ($2::uuid IS NULL OR EXISTS (SELECT 1 FROM folders WHERE id = $2 AND user_id = $3))",
)
.bind(message_ids)
.bind(folder_id)
.bind(user_id)
.execute(&mut **tx)
.await?;
}
Action::Archive => {
let archive = archive_folder(tx, user_id).await?;
sqlx::query("UPDATE messages SET folder_id = $2 WHERE id = ANY($1)")
.bind(message_ids)
.bind(archive)
.execute(&mut **tx)
.await?;
}
Action::MarkRead => {
sqlx::query(
r#"UPDATE messages SET flags = array_append(flags, '\Seen')
WHERE id = ANY($1) AND NOT ('\Seen' = ANY(flags))"#,
)
.bind(message_ids)
.execute(&mut **tx)
.await?;
}
Action::MarkUnread => {
sqlx::query(r#"UPDATE messages SET flags = array_remove(flags, '\Seen') WHERE id = ANY($1)"#)
.bind(message_ids)
.execute(&mut **tx)
.await?;
}
Action::Delete => {
sqlx::query("UPDATE messages SET deleted_at = now() WHERE id = ANY($1) AND deleted_at IS NULL")
.bind(message_ids)
.execute(&mut **tx)
.await?;
}
Action::Restore => {
sqlx::query("UPDATE messages SET deleted_at = NULL WHERE id = ANY($1)")
.bind(message_ids)
.execute(&mut **tx)
.await?;
}
}
}
Ok(())
}
/// The user's Archive folder, created on first use. An existing folder the
/// user happened to name "Archive" is adopted rather than colliding with it.
pub async fn archive_folder(
tx: &mut Transaction<'_, Postgres>,
user_id: Uuid,
) -> sqlx::Result<Uuid> {
if let Some((id,)) = sqlx::query_as::<_, (Uuid,)>(
"SELECT id FROM folders WHERE user_id = $1 AND role = 'archive'",
)
.bind(user_id)
.fetch_optional(&mut **tx)
.await?
{
return Ok(id);
}
let (id,): (Uuid,) = sqlx::query_as(
"INSERT INTO folders (user_id, name, role) VALUES ($1, 'Archive', 'archive') \
ON CONFLICT (user_id, name) DO UPDATE SET role = 'archive' \
RETURNING id",
)
.bind(user_id)
.fetch_one(&mut **tx)
.await?;
Ok(id)
}
/// Whether every tag and folder an action list references belongs to the
/// user — checked when a rule is saved or a manual action is requested.
pub async fn check_targets(pool: &PgPool, user_id: Uuid, actions: &[Action]) -> Result<(), String> {
for a in actions {
let (table, id) = match a {
Action::Tag { tag_id } | Action::Untag { tag_id } => ("tags", *tag_id),
Action::Move { folder_id: Some(f) } => ("folders", *f),
_ => continue,
};
let exists: bool = sqlx::query_scalar(&format!(
"SELECT EXISTS (SELECT 1 FROM {table} WHERE id = $1 AND user_id = $2)"
))
.bind(id)
.bind(user_id)
.fetch_one(pool)
.await
.map_err(|e| e.to_string())?;
if !exists {
return Err(format!("{} {id} not found", &table[..table.len() - 1]));
}
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
fn facts() -> Facts {
Facts {
from: "Newsletter <news@lists.example.com>".into(),
to: "alice@example.com".into(),
cc: "team@example.com".into(),
subject: "Your WEEKLY digest".into(),
body: "Unsubscribe at the bottom".into(),
headers: vec![
("list-id".into(), "<weekly.lists.example.com>".into()),
("x-spam-score".into(), "5.3".into()),
("x-spam-status".into(), "Yes, score=7.25 required=5".into()),
("received".into(), "from a".into()),
("received".into(), "from relay.example.net".into()),
],
}
}
fn test(field: Field, op: Op, value: &str) -> Test {
Test {
field,
header: None,
op,
value: value.into(),
negate: false,
}
}
fn header(name: &str, op: Op, value: &str) -> Test {
Test {
field: Field::Header,
header: Some(name.into()),
op,
value: value.into(),
negate: false,
}
}
fn rule(match_: Match, tests: Vec<Test>) -> CompiledRule {
CompiledRule::compile(
Uuid::nil(),
Conditions { match_, tests },
vec![Action::MarkRead],
)
.unwrap()
}
#[test]
fn contains_and_equals_ignore_case() {
assert!(rule(
Match::All,
vec![test(Field::Subject, Op::Contains, "weekly")]
)
.matches(&facts()));
assert!(rule(
Match::All,
vec![test(Field::To, Op::Equals, "ALICE@example.com")]
)
.matches(&facts()));
}
#[test]
fn all_needs_every_test_any_needs_one() {
let hit = test(Field::Subject, Op::Contains, "digest");
let miss = test(Field::Subject, Op::Contains, "invoice");
assert!(!rule(Match::All, vec![hit.clone(), miss.clone()]).matches(&facts()));
assert!(rule(Match::Any, vec![hit, miss]).matches(&facts()));
}
#[test]
fn negate_inverts_a_test() {
let mut t = test(Field::From, Op::Contains, "lists.example.com");
t.negate = true;
assert!(!rule(Match::All, vec![t]).matches(&facts()));
}
#[test]
fn recipients_covers_to_and_cc() {
assert!(rule(
Match::All,
vec![test(Field::Recipients, Op::Contains, "team@")]
)
.matches(&facts()));
assert!(!rule(Match::All, vec![test(Field::To, Op::Contains, "team@")]).matches(&facts()));
}
#[test]
fn header_names_are_case_insensitive_and_repeats_are_all_checked() {
assert!(rule(
Match::All,
vec![header("List-ID", Op::Contains, "weekly.lists")]
)
.matches(&facts()));
assert!(rule(
Match::All,
vec![header("Received", Op::Contains, "relay.example.net")]
)
.matches(&facts()));
assert!(!rule(Match::All, vec![header("X-Missing", Op::Exists, "")]).matches(&facts()));
}
#[test]
fn numeric_comparison_reads_the_first_number() {
// Both plain and "Yes, score=N" formats — the phase 6 spam headers.
assert!(rule(
Match::All,
vec![header("X-Spam-Score", Op::GreaterThan, "5")]
)
.matches(&facts()));
assert!(rule(
Match::All,
vec![header("X-Spam-Status", Op::GreaterThan, "7")]
)
.matches(&facts()));
assert!(!rule(
Match::All,
vec![header("X-Spam-Score", Op::GreaterThan, "6")]
)
.matches(&facts()));
assert!(
rule(Match::All, vec![header("X-Spam-Score", Op::LessThan, "6")]).matches(&facts())
);
}
#[test]
fn regex_is_case_insensitive() {
assert!(rule(
Match::All,
vec![test(Field::Subject, Op::Matches, r"^your\s+weekly")]
)
.matches(&facts()));
}
#[test]
fn validation_rejects_bad_rules() {
let bad = |tests: Vec<Test>, actions: Vec<Action>| {
validate(
&Conditions {
match_: Match::All,
tests,
},
&actions,
true,
)
.is_err()
};
assert!(bad(vec![], vec![Action::MarkRead]), "no conditions");
assert!(
bad(vec![test(Field::Subject, Op::Contains, "x")], vec![]),
"no actions"
);
assert!(
bad(
vec![test(Field::Subject, Op::Matches, "(unclosed")],
vec![Action::MarkRead]
),
"bad regex"
);
assert!(
bad(
vec![test(Field::Subject, Op::GreaterThan, "lots")],
vec![Action::MarkRead]
),
"non-numeric"
);
assert!(
bad(vec![header("", Op::Exists, "")], vec![Action::MarkRead]),
"header without a name"
);
assert!(
bad(
vec![test(Field::Subject, Op::Contains, "")],
vec![Action::MarkRead]
),
"empty contains"
);
assert!(
bad(
vec![test(Field::Subject, Op::Contains, "x")],
vec![Action::Restore]
),
"restore isn't a rule action"
);
}
#[test]
fn oversized_patterns_are_rejected() {
// Compiles to far more than the size limit.
let huge = format!("({}){{50}}", "[a-z]{1,500}");
assert!(compile_pattern(&huge).is_err());
}
#[test]
fn actions_round_trip_through_json_as_tagged_objects() {
let a = vec![Action::Archive, Action::Move { folder_id: None }];
let json = serde_json::to_string(&a).unwrap();
assert_eq!(
json,
r#"[{"type":"archive"},{"type":"move","folder_id":null}]"#
);
assert_eq!(serde_json::from_str::<Vec<Action>>(&json).unwrap(), a);
}
#[test]
fn stop_is_no_longer_an_action() {
// It's a rule option now (stop_after_match). A submitted
// {"type":"stop"} must be rejected rather than silently ignored.
assert!(serde_json::from_str::<Action>(r#"{"type":"stop"}"#).is_err());
}
#[test]
fn only_header_tests_need_a_reparse() {
assert!(!rule(Match::All, vec![test(Field::Subject, Op::Contains, "x")]).needs_headers());
assert!(rule(
Match::Any,
vec![
test(Field::Subject, Op::Contains, "x"),
header("List-Id", Op::Exists, "")
]
)
.needs_headers());
}
}
+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())
}
+372
View File
@@ -0,0 +1,372 @@
//! 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?;
crate::threading::assign(
&mut tx,
&crate::threading::ThreadInput {
account_id: item.account_id,
row_id: message_row_id,
message_id: item.message_id.as_deref(),
in_reply_to: item.in_reply_to.as_deref(),
references: &item.references_,
subject: Some(&item.subject),
},
)
.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(_)
));
}
}
+16 -1
View File
@@ -35,7 +35,22 @@ impl BlobStore {
let hash = Self::hash(data);
let full_path = self.path_for_hash(&hash);
if !tokio::fs::try_exists(&full_path).await.unwrap_or(false) {
if tokio::fs::try_exists(&full_path).await.unwrap_or(false) {
// Reusing an existing file refreshes its mtime: the trash purge
// won't remove a blob touched within its grace period, which
// covers the gap between this write and the row that will
// reference it being inserted.
let path = full_path.clone();
tokio::task::spawn_blocking(move || {
std::fs::File::options()
.write(true)
.open(&path)
.and_then(|f| f.set_modified(std::time::SystemTime::now()))
})
.await
.context("touching existing blob")?
.with_context(|| format!("touching blob {}", full_path.display()))?;
} else {
if let Some(parent) = full_path.parent() {
tokio::fs::create_dir_all(parent)
.await
+306
View File
@@ -0,0 +1,306 @@
//! Conversation threading (server-architecture-spec.md §3.6).
//!
//! An incremental, database-backed take on JWZ. Rather than rebuilding every
//! thread tree in memory, each message is linked as it arrives:
//!
//! 1. **Ancestors** — messages whose Message-ID appears in its References
//! or In-Reply-To.
//! 2. **Children that arrived first** — messages whose References or
//! In-Reply-To name *it*. IDLE delivers mail in arrival order, not thread
//! order, so a reply can land before its parent.
//! 3. **Siblings of a missing ancestor** — messages that reference any of
//! the same IDs. This is what JWZ's placeholder containers achieve: two
//! replies to a message we never received still belong together.
//!
//! Every thread those turn up is merged into one. The survivor is the
//! thread holding the oldest message, which keeps repeated merges
//! deterministic. That's also why thread_id is its own generated ID rather
//! than the root's Message-ID: a thread can gain an earlier root later.
//!
//! When a message carries no reference headers at all, a subject fallback
//! applies — but only when the subject marks it as a reply (Re:/Fwd:). Some
//! mailing lists strip References, and their replies should still group;
//! unrelated mail that merely shares a generic subject like "Invoice"
//! must not.
//!
//! Scoped per account: a thread never spans two accounts (§3.6).
use crate::smtp::compose::bare_id;
use sqlx::{Postgres, Transaction};
use uuid::Uuid;
/// Raise this when the algorithm changes; accounts below it are re-threaded
/// once on their next sync start.
pub const THREADING_VERSION: i32 = 1;
const SUBJECT_FALLBACK_DAYS: i32 = 30;
const REPLY_PREFIXES: &[&str] = &[
"re", "fw", "fwd", "aw", "wg", "sv", "vs", "antw", "odp", "pd",
];
/// Strips reply/forward prefixes (`Re:`, `Fwd:`, `AW:`, `Re[2]:`…) and
/// mailing-list tags (`[list-name]`) from the front, repeatedly, then
/// lowercases and collapses whitespace.
pub fn normalize_subject(subject: &str) -> String {
let mut s = subject.trim();
loop {
let before = s;
if let Some(rest) = s.strip_prefix('[') {
if let Some(end) = rest.find(']') {
s = rest[end + 1..].trim_start();
}
}
if let Some(rest) = strip_reply_prefix(s) {
s = rest.trim_start();
}
if s == before {
break;
}
}
s.split_whitespace()
.collect::<Vec<_>>()
.join(" ")
.to_lowercase()
}
/// Does the subject start with a reply/forward marker (after any list tag)?
pub fn is_reply_subject(subject: &str) -> bool {
let mut s = subject.trim();
while let Some(rest) = s.strip_prefix('[') {
match rest.find(']') {
Some(end) => s = rest[end + 1..].trim_start(),
None => break,
}
}
strip_reply_prefix(s).is_some()
}
fn strip_reply_prefix(s: &str) -> Option<&str> {
let colon = s.find(':')?;
let head = s[..colon].trim();
// Allow a counter, as in "Re[2]:" or "Re(2):".
let word = head.split(['[', '(']).next().unwrap_or("").trim();
if head.len() <= 10 && REPLY_PREFIXES.iter().any(|p| word.eq_ignore_ascii_case(p)) {
Some(&s[colon + 1..])
} else {
None
}
}
pub struct ThreadInput<'a> {
pub account_id: Uuid,
pub row_id: Uuid,
pub message_id: Option<&'a str>,
pub in_reply_to: Option<&'a str>,
pub references: &'a [String],
pub subject: Option<&'a str>,
}
/// Links one message into its thread, merging threads where it bridges
/// them. Returns the thread it ended up in.
pub async fn assign(
tx: &mut Transaction<'_, Postgres>,
input: &ThreadInput<'_>,
) -> sqlx::Result<Uuid> {
let own_id = input.message_id.map(bare_id).filter(|s| !s.is_empty());
let mut candidates: Vec<String> = input
.references
.iter()
.map(|r| bare_id(r))
.chain(input.in_reply_to.map(bare_id))
.filter(|r| !r.is_empty() && Some(r) != own_id.as_ref())
.collect();
candidates.sort();
candidates.dedup();
let subject_norm = input
.subject
.map(normalize_subject)
.filter(|s| !s.is_empty());
sqlx::query("UPDATE messages SET subject_norm = $2 WHERE id = $1")
.bind(input.row_id)
.bind(&subject_norm)
.execute(&mut **tx)
.await?;
let mut related: Vec<(Uuid,)> = sqlx::query_as(
"SELECT DISTINCT thread_id FROM messages \
WHERE account_id = $1 AND id <> $2 AND ( \
message_id = ANY($3) \
OR in_reply_to = ANY($3) \
OR references_ && $3 \
OR ($4::text IS NOT NULL AND (in_reply_to = $4 OR $4 = ANY(references_))) \
)",
)
.bind(input.account_id)
.bind(input.row_id)
.bind(&candidates)
.bind(&own_id)
.fetch_all(&mut **tx)
.await?;
if related.is_empty() && candidates.is_empty() {
if let (Some(norm), Some(subject)) = (&subject_norm, input.subject) {
if is_reply_subject(subject) {
related = sqlx::query_as(
"SELECT thread_id FROM messages \
WHERE account_id = $1 AND id <> $2 AND subject_norm = $3 \
AND COALESCE(sent_at, created_at) > now() - make_interval(days => $4) \
ORDER BY COALESCE(sent_at, created_at) DESC LIMIT 1",
)
.bind(input.account_id)
.bind(input.row_id)
.bind(norm)
.bind(SUBJECT_FALLBACK_DAYS)
.fetch_all(&mut **tx)
.await?;
}
}
}
let (own_thread,): (Uuid,) = sqlx::query_as("SELECT thread_id FROM messages WHERE id = $1")
.bind(input.row_id)
.fetch_one(&mut **tx)
.await?;
let mut threads: Vec<Uuid> = related.into_iter().map(|(t,)| t).collect();
threads.push(own_thread);
threads.sort();
threads.dedup();
if threads.len() == 1 {
return Ok(own_thread);
}
// Survivor: the thread holding the oldest message.
let (survivor,): (Uuid,) = sqlx::query_as(
"SELECT thread_id FROM messages WHERE account_id = $1 AND thread_id = ANY($2) \
ORDER BY COALESCE(sent_at, created_at) ASC, created_at ASC LIMIT 1",
)
.bind(input.account_id)
.bind(&threads)
.fetch_one(&mut **tx)
.await?;
sqlx::query(
"UPDATE messages SET thread_id = $3 \
WHERE account_id = $1 AND thread_id = ANY($2) AND thread_id <> $3",
)
.bind(input.account_id)
.bind(&threads)
.bind(survivor)
.execute(&mut **tx)
.await?;
// Drafts and queued replies point at a thread too; keep them attached.
sqlx::query("UPDATE outbox SET thread_id = $2 WHERE thread_id = ANY($1) AND thread_id <> $2")
.bind(&threads)
.bind(survivor)
.execute(&mut **tx)
.await?;
Ok(survivor)
}
#[derive(sqlx::FromRow)]
struct ThreadingRow {
id: Uuid,
message_id: Option<String>,
in_reply_to: Option<String>,
references_: Vec<String>,
subject: Option<String>,
}
/// Re-threads an account's existing mail, oldest first, when its
/// threading version is behind. One transaction per message keeps locks
/// short on a large mailbox; an interrupted run just repeats next time,
/// since linking a message twice is harmless.
pub async fn backfill_if_needed(pool: &sqlx::PgPool, account_id: Uuid) -> anyhow::Result<()> {
let version: Option<(i32,)> =
sqlx::query_as("SELECT threading_version FROM sync_state WHERE account_id = $1")
.bind(account_id)
.fetch_optional(pool)
.await?;
if version.map(|(v,)| v >= THREADING_VERSION).unwrap_or(true) {
return Ok(());
}
let rows: Vec<ThreadingRow> = sqlx::query_as(
"SELECT id, message_id, in_reply_to, references_, subject FROM messages \
WHERE account_id = $1 ORDER BY COALESCE(sent_at, created_at) ASC, created_at ASC",
)
.bind(account_id)
.fetch_all(pool)
.await?;
tracing::info!(%account_id, messages = rows.len(), "re-threading existing mail");
for row in &rows {
let mut tx = pool.begin().await?;
assign(
&mut tx,
&ThreadInput {
account_id,
row_id: row.id,
message_id: row.message_id.as_deref(),
in_reply_to: row.in_reply_to.as_deref(),
references: &row.references_,
subject: row.subject.as_deref(),
},
)
.await?;
tx.commit().await?;
}
sqlx::query("UPDATE sync_state SET threading_version = $2 WHERE account_id = $1")
.bind(account_id)
.bind(THREADING_VERSION)
.execute(pool)
.await?;
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn strips_stacked_reply_prefixes_and_list_tags() {
assert_eq!(normalize_subject("Re: Fwd: RE: Roof quote"), "roof quote");
assert_eq!(
normalize_subject("[tern-dev] Re: [tern-dev] Build broke"),
"build broke"
);
assert_eq!(
normalize_subject("AW: Re[2]: Termin morgen"),
"termin morgen"
);
assert_eq!(normalize_subject("Re(3): hello"), "hello");
}
#[test]
fn leaves_colons_that_are_not_prefixes() {
assert_eq!(
normalize_subject("Meeting: Q3 planning"),
"meeting: q3 planning"
);
assert_eq!(
normalize_subject("Ticket 1234: server down"),
"ticket 1234: server down"
);
}
#[test]
fn reply_detection_sees_through_list_tags_only() {
assert!(is_reply_subject("Re: invoice"));
assert!(is_reply_subject("[list] Fwd: invoice"));
assert!(!is_reply_subject("Invoice"));
assert!(!is_reply_subject("Meeting: Re-planning"));
}
#[test]
fn empty_and_prefix_only_subjects_normalise_to_empty() {
assert_eq!(normalize_subject(""), "");
assert_eq!(normalize_subject("Re:"), "");
}
}
+119
View File
@@ -0,0 +1,119 @@
//! 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,
trash_retention_days: 30,
},
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")),
("POST", format!("/api/threads/{id}/actions")),
("PUT", format!("/api/folders/{id}")),
("DELETE", format!("/api/folders/{id}")),
("PUT", format!("/api/tags/{id}")),
("DELETE", format!("/api/tags/{id}")),
("PUT", format!("/api/rules/{id}")),
("DELETE", format!("/api/rules/{id}")),
("POST", format!("/api/rules/{id}/run")),
] {
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",
"/api/tags",
"/api/rules",
] {
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"
);
}