2 Commits
Author SHA1 Message Date
Mateusz PstruchaandClaude Opus 5.5 77c1813539 Bump to 0.6.0
CI / test (push) Successful in 4m30s
Release / image (push) Successful in 3m4s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-23 15:37:28 +02:00
Mateusz PstruchaandClaude Opus 5.5 e2bee05b30 Add spam scoring and Junk; fix IDLE race and thread paging
CI / test (push) Successful in 4m8s
Spam (§3.5, phase 6): each message's score is extracted at ingest from
whichever filter header it carries — PMG's folded X-SPAM-LEVEL
"Spam detection results: N", X-Spam-Score, X-Spam-Status score=N, or
SpamAssassin's X-Spam-Level star bar. PMG and SpamAssassin use that same
header name for different formats, so each format is matched explicitly
rather than taking the first number. No spam header means "unknown", not
0; a spam-score rule condition treats it as neither over nor under a
threshold. A Junk system folder and `junk` action join Archive; run-now
re-parses stored mail that predates score extraction.

Fix: mail announced during a fetch could wait for the next IDLE renewal.
A server announces new mail once, as an untagged EXISTS on whatever
response is in flight; async-imap files those in a side channel rather
than waking IDLE, and the server never repeats them. Measured with
bursts separated by quiet gaps: 4 of 12 bursts left a message stuck for
the whole gap before, 0 of 12 (worst 0.2s) after. The loop now drains
that channel once IDLE has started. IDLE renewal drops from 25 to 10
minutes, doubling as the spec's safety-net poll (§3.1).

Fix: thread paging and sorting could hide mail.
- The cursor was a bare timestamp compared with `<`; Date headers have
  one-second resolution, so threads tied with a page's last row were
  skipped. It's now a keyset of (sort time, thread id).
- With no cursor the query defaulted to before=now(), so future-dated
  mail never appeared; undated mail had a NULL sort key and never
  appeared either. The sort key is now LEAST(COALESCE(sent_at,
  created_at), created_at): the Date header, clamped to arrival time.
- next_cursor is null on the last page.
Verified: 121 inbox threads walked in pages of 17 with no gaps or
duplicates; future-dated and undated mail visible.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-23 15:32:35 +02:00
9 changed files with 448 additions and 40 deletions

No files matched your search

Generated
+2 -1
View File
@@ -2687,10 +2687,11 @@ dependencies = [
[[package]]
name = "tern-server"
version = "0.5.0"
version = "0.6.0"
dependencies = [
"anyhow",
"argon2",
"async-channel 2.5.0",
"async-imap",
"async-native-tls",
"axum",
+2 -1
View File
@@ -1,6 +1,6 @@
[package]
name = "tern-server"
version = "0.5.0"
version = "0.6.0"
edition = "2021"
description = "Tern sync server — the only component that speaks IMAP/SMTP"
@@ -13,6 +13,7 @@ tower-http = { version = "0.6", features = ["trace", "cors"] }
sqlx = { version = "0.8", features = ["runtime-tokio", "tls-rustls", "postgres", "chrono", "uuid", "migrate"] }
async-imap = { version = "0.11", default-features = false, features = ["runtime-tokio"] }
async-channel = "2" # same major as async-imap uses, for its unsolicited-response channel
async-native-tls = { version = "0.6", default-features = false, features = ["runtime-tokio"] }
mail-parser = "0.11"
mail-send = "0.4"
+28 -2
View File
@@ -2,7 +2,7 @@
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–5)
## What's built (build-order phases 1–6)
- **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.
@@ -11,7 +11,8 @@ The sync server for [Tern](../) — the only component that ever speaks IMAP/SMT
- **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.
- **Spam filtering** (`src/spam.rs`, §3.5) — every message's spam score is extracted at ingest from whichever filter header it carries, and a *spam score* rule condition compares it numerically. The webapp's **Add spam filter** creates the spec's threshold rule — score over 5 → Junk, placed first, stopping later rules — as an ordinary rule you can edit. Junk is a system folder like Archive.
- **Tags, folders and views** — thread listing takes `view=inbox|all|sent|junk|trash|folder|tag`, paged by an opaque keyset cursor. 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
@@ -23,6 +24,23 @@ The sync server for [Tern](../) — the only component that ever speaks IMAP/SMT
- **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.
## Spam scores
Proxmox Mail Gateway runs SpamAssassin, and header names are configurable, so the extractor recognises each format seen in practice rather than one fixed header — in order of precision:
| Header | Example | Read as |
|---|---|---|
| `X-SPAM-LEVEL` (PMG) | `Spam detection results: 8` followed by per-rule scores, folded over several lines | the total, 8 |
| `X-Spam-Score` | `5.3` | 5.3 |
| `X-Spam-Status` | `Yes, score=7.2 required=5.0 …` | 7.2 |
| `X-Spam-Level` (SpamAssassin) | `*******` | 7 (one per star) |
The first and last rows are the same header name — PMG and SpamAssassin use it for completely different formats — which is why each format is matched explicitly rather than taking "the first number in the header".
**PMG only adds its header from spam level 3 by default**, so mail below that has no score at all. That's stored as "unknown", not 0, and a rule treats it as neither over nor under any threshold. Thresholds of 3 and above work as expected; to act on lower scores, change PMG's rule that adds the header.
Scores are extracted for mail ingested from this version on. Older mail has none stored, but *run now* still finds it: when a stored score is missing it re-reads the raw message.
## 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.
@@ -49,6 +67,14 @@ Also deferred, and worth knowing because they aren't obvious from the code:
- **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.
### Fixed: mail announced mid-fetch could wait for the next renewal
A server announces new mail once per session, as an untagged `EXISTS` attached to whatever response is in flight. Mail landing while Tern was fetching — or while IDLE was starting — was announced that way; async-imap files such announcements in a side channel instead of waking IDLE, and the server doesn't repeat them. The message then sat unfetched until the next IDLE renewal or the next new mail.
Measured before the fix: in bursts of 4 messages separated by quiet gaps, 4 of 12 bursts had a message stuck for the whole gap; one message sat 358 s in an earlier run. After: 0 of 12, worst case 0.2 s. The sync loop now drains that channel after IDLE starts and fetches again if it announced mail. Draining also matters on its own — the channel holds 100 entries and silently drops announcements once full.
IDLE is also renewed every 10 minutes rather than 25; each renewal re-runs the fetch pass, so it doubles as the 5–15 minute safety-net poll the spec asks for (§3.1).
### Decided: the sync engine only moves forward
`fetch_new_headers` only looks at UIDs above `last_synced_uid`, so **flag changes and deletions made on the source IMAP server are never noticed.** A message read or deleted in another client stays unread and present in Tern forever.
+4
View File
@@ -0,0 +1,4 @@
-- Phase 6: a system Junk folder alongside Archive (server-architecture-spec.md
-- §3.5 — "score > N → tag as spam / move to Junk").
ALTER TABLE folders DROP CONSTRAINT folders_role_check;
ALTER TABLE folders ADD CONSTRAINT folders_role_check CHECK (role IN ('archive', 'junk'));
+91 -12
View File
@@ -34,6 +34,8 @@ pub enum View {
All,
Sent,
Trash,
/// The system Junk folder, which may not exist yet.
Junk,
Folder,
Tag,
}
@@ -45,6 +47,7 @@ impl View {
View::All => "all",
View::Sent => "sent",
View::Trash => "trash",
View::Junk => "junk",
View::Folder => "folder",
View::Tag => "tag",
}
@@ -57,17 +60,45 @@ pub struct ListThreadsQuery {
pub view: View,
pub folder_id: Option<Uuid>,
pub tag_id: Option<Uuid>,
pub before: Option<DateTime<Utc>>,
/// Opaque cursor from a previous page's `next_cursor`.
pub before: Option<String>,
pub limit: Option<i64>,
}
/// Keyset position: the last row's sort time plus its thread id. The id
/// breaks ties — sort times come from Date headers with one-second
/// resolution, so a burst of mail shares them, and a timestamp-only cursor
/// with `<` would skip every thread tied with the last row of a page.
struct Cursor {
at: DateTime<Utc>,
thread_id: Uuid,
}
impl Cursor {
fn encode(at: DateTime<Utc>, thread_id: Uuid) -> String {
format!(
"{}|{thread_id}",
at.to_rfc3339_opts(chrono::SecondsFormat::Micros, true)
)
}
fn decode(s: &str) -> Option<Self> {
let (at, id) = s.split_once('|')?;
Some(Cursor {
at: DateTime::parse_from_rfc3339(at).ok()?.with_timezone(&Utc),
thread_id: id.parse().ok()?,
})
}
}
#[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>>,
/// When the newest message arrived, by the sort key described in `list`.
pub last_message_at: DateTime<Utc>,
pub message_count: i64,
pub unread_count: i64,
pub has_attachments: bool,
@@ -80,7 +111,8 @@ pub struct ThreadSummary {
#[derive(Serialize)]
pub struct ListThreadsResponse {
pub threads: Vec<ThreadSummary>,
pub next_cursor: Option<DateTime<Utc>>,
/// None when this was the last page.
pub next_cursor: Option<String>,
}
pub async fn list(
@@ -89,7 +121,12 @@ pub async fn list(
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);
let cursor = match q.before.as_deref() {
Some(raw) => {
Some(Cursor::decode(raw).ok_or_else(|| ApiError::BadRequest("invalid cursor".into()))?)
}
None => None,
};
match q.view {
View::Folder if q.folder_id.is_none() => {
return Err(ApiError::BadRequest("view=folder needs folder_id".into()))
@@ -102,10 +139,19 @@ pub async fn list(
// 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.
//
// Threads sort by `sort_at` = LEAST(COALESCE(sent_at, created_at),
// created_at): the Date header, but never later than when we received
// the message. A mail with no Date header still sorts (by arrival), and
// one dated in the future — clock skew, or spam trying to pin itself to
// the top — is clamped to its arrival time. An older mailbox synced
// for the first time keeps its real chronology, since its Date headers
// all precede the sync.
let threads: Vec<ThreadSummary> = sqlx::query_as(
r#"
WITH mine AS (
SELECT m.* FROM messages m
SELECT m.*, LEAST(COALESCE(m.sent_at, m.created_at), m.created_at) AS sort_at
FROM messages m
JOIN accounts a ON a.id = m.account_id
WHERE a.user_id = $1
),
@@ -116,6 +162,8 @@ pub async fn list(
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 'junk' THEN v.deleted_at IS NULL AND v.folder_id =
(SELECT id FROM folders WHERE user_id = $1 AND role = 'junk')
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)
@@ -130,11 +178,11 @@ pub async fn list(
-- 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.sort_at ASC,
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,
ORDER BY m.sort_at DESC))[1] AS last_from,
MAX(m.sort_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,
@@ -149,8 +197,8 @@ pub async fn list(
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
HAVING $5::timestamptz IS NULL OR (MAX(m.sort_at), m.thread_id) < ($5, $8)
ORDER BY last_message_at DESC, m.thread_id DESC
LIMIT $6
"#,
)
@@ -158,13 +206,17 @@ pub async fn list(
.bind(q.view.as_str())
.bind(q.folder_id)
.bind(q.tag_id)
.bind(before)
.bind(cursor.as_ref().map(|c| c.at))
.bind(limit)
.bind(state.config.trash_retention_days as i32)
.bind(cursor.as_ref().map(|c| c.thread_id))
.fetch_all(&state.pool)
.await?;
let next_cursor = threads.last().and_then(|t| t.last_message_at);
let next_cursor = (threads.len() as i64 == limit)
.then(|| threads.last())
.flatten()
.map(|t| Cursor::encode(t.last_message_at, t.thread_id));
Ok(Json(ListThreadsResponse {
threads,
@@ -232,3 +284,30 @@ pub async fn mark_read(
)
.await
}
#[cfg(test)]
mod tests {
use super::Cursor;
#[test]
fn cursor_round_trips_with_microseconds_and_id() {
let at = chrono::DateTime::parse_from_rfc3339("2026-09-23T10:08:20.123456Z")
.unwrap()
.with_timezone(&chrono::Utc);
let id = uuid::Uuid::new_v4();
let c = Cursor::decode(&Cursor::encode(at, id)).unwrap();
assert_eq!((c.at, c.thread_id), (at, id));
}
#[test]
fn malformed_cursors_are_rejected() {
for bad in [
"",
"2026-09-23T10:08:20Z",
"nonsense|also-nonsense",
"2026-09-23T10:08:20Z|not-a-uuid",
] {
assert!(Cursor::decode(bad).is_none(), "{bad:?}");
}
}
}
+41 -3
View File
@@ -25,9 +25,26 @@ use sqlx::PgPool;
use std::time::Duration;
use uuid::Uuid;
/// Re-issue IDLE this often even if the server hasn't timed out, and treat a
/// connection as stalled if nothing happens for this long.
const IDLE_RENEW: Duration = Duration::from_secs(25 * 60);
/// Re-issue IDLE this often even if nothing happened. Each renewal re-runs
/// the fetch pass, so it doubles as the safety-net poll the spec asks for
/// (§3.1, 5–15 min) in case a notification is ever lost — and keeps well
/// inside the ~30 min after which servers drop an IDLE session.
const IDLE_RENEW: Duration = Duration::from_secs(10 * 60);
/// Empties async-imap's side channel of unsolicited responses, reporting
/// whether any of them announced new mail. Draining also matters on its
/// own: the channel holds 100 entries and silently drops announcements once
/// full, which an undrained long-lived session eventually reaches.
fn announced_new_mail(
notices: &async_channel::Receiver<async_imap::types::UnsolicitedResponse>,
) -> bool {
use async_imap::types::UnsolicitedResponse as U;
let mut new_mail = false;
while let Ok(notice) = notices.try_recv() {
new_mail |= matches!(notice, U::Exists(_) | U::Recent(_));
}
new_mail
}
const BODY_FETCH_BATCH: i64 = 25;
type ImapSession = async_imap::Session<async_native_tls::TlsStream<tokio::net::TcpStream>>;
@@ -388,6 +405,12 @@ impl AccountSyncer {
.await?;
}
sqlx::query("UPDATE messages SET spam_score = $2 WHERE id = $1")
.bind(message_row_id)
.bind(crate::spam::extract_score(&parsed.headers).map(|s| s as f32))
.execute(&mut *tx)
.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.
@@ -423,6 +446,8 @@ impl AccountSyncer {
/// caller can keep using it. `Session::idle()` takes the session by
/// value; `Handle::done()` gives it back once IDLE ends.
async fn idle_until_change(&self, session: ImapSession) -> Result<(bool, ImapSession)> {
// Cloned before idle() takes the session, so it can be read mid-IDLE.
let notices = session.unsolicited_responses.clone();
let mut handle = session.idle();
if let Err(e) = handle.init().await {
tracing::warn!(account_id = %self.account.id, error = %e, "server rejected IDLE, falling back to polling");
@@ -433,6 +458,19 @@ impl AccountSyncer {
return Ok((false, session));
}
// A server announces new mail once per session, as an untagged
// EXISTS attached to whatever response is in flight. Mail landing
// during our own fetches, or while IDLE was starting up, was
// announced that way — async-imap files those in a side channel
// rather than waking IDLE, and the server won't repeat them. The
// wait below only sees responses from here on, so without this the
// message would sit unfetched until the next renewal.
if announced_new_mail(&notices) {
tracing::debug!(account_id = %self.account.id, "new mail announced before IDLE began");
let session = handle.done().await.context("DONE after IDLE failed")?;
return Ok((true, session));
}
let (idle_wait, _stop_source) = handle.wait_with_timeout(IDLE_RENEW);
let wait_result = idle_wait.await;
+1
View File
@@ -9,5 +9,6 @@ pub mod models;
pub mod retention;
pub mod rules;
pub mod smtp;
pub mod spam;
pub mod storage;
pub mod threading;
+145 -21
View File
@@ -45,9 +45,11 @@ pub enum Field {
Recipients,
Subject,
Body,
/// Any header by name, e.g. List-Id, or the PMG spam headers phase 6
/// will use.
/// Any header by name, e.g. List-Id.
Header,
/// The spam filter's score, read from whichever spam header the
/// message carries (see `crate::spam`). Numeric comparisons only.
SpamScore,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
@@ -97,6 +99,9 @@ pub enum Action {
folder_id: Option<Uuid>,
},
Archive,
/// Move to the system Junk folder — "report spam". Not-spam is a
/// `move` back to the inbox.
Junk,
MarkRead,
MarkUnread,
/// Soft delete — to Trash, restorable.
@@ -111,6 +116,7 @@ impl Action {
Action::Tag { .. }
| Action::Move { .. }
| Action::Archive
| Action::Junk
| Action::MarkRead
| Action::Delete
)
@@ -126,6 +132,9 @@ pub struct Facts {
pub body: String,
/// Lowercased names; a header can repeat (Received, …).
pub headers: Vec<(String, String)>,
/// None when the message carries no spam header at all — PMG only adds
/// one from spam level 3 by default — which is "not flagged", not 0.
pub spam_score: Option<f64>,
}
impl Facts {
@@ -142,6 +151,7 @@ impl Facts {
.or_else(|| p.html_body.clone())
.unwrap_or_default(),
headers: p.headers.clone(),
spam_score: crate::spam::extract_score(&p.headers),
}
}
}
@@ -183,6 +193,13 @@ pub fn validate(conditions: &Conditions, actions: &[Action], for_rule: bool) ->
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());
}
if t.field == Field::SpamScore
&& !matches!(t.op, Op::GreaterThan | Op::LessThan | Op::Exists)
{
return Err(
"spam score can only be compared as a number (greater than, less than) or tested for presence".into(),
);
}
match t.op {
Op::Matches => {
compile_pattern(&t.value)?;
@@ -241,7 +258,7 @@ impl CompiledRule {
self.conditions
.tests
.iter()
.any(|t| t.field == Field::Header)
.any(|t| matches!(t.field, Field::Header | Field::SpamScore))
}
pub fn matches(&self, facts: &Facts) -> bool {
@@ -259,6 +276,17 @@ impl CompiledRule {
}
fn eval_test(t: &Test, re: Option<&Regex>, facts: &Facts) -> bool {
if t.field == Field::SpamScore {
let threshold = t.value.trim().parse::<f64>().ok();
return match (&t.op, facts.spam_score, threshold) {
(Op::Exists, score, _) => score.is_some(),
(Op::GreaterThan, Some(score), Some(n)) => score > n,
(Op::LessThan, Some(score), Some(n)) => score < n,
// No score means the filter didn't flag it: not over any
// threshold, and — deliberately — not "under" one either.
_ => false,
};
}
let recipients;
let values: Vec<&str> = match t.field {
Field::From => vec![&facts.from],
@@ -270,6 +298,7 @@ fn eval_test(t: &Test, re: Option<&Regex>, facts: &Facts) -> bool {
}
Field::Subject => vec![&facts.subject],
Field::Body => vec![&facts.body],
Field::SpamScore => unreachable!("spam score is compared numerically above"),
Field::Header => {
let name = t.header.as_deref().unwrap_or("").trim().to_lowercase();
facts
@@ -350,6 +379,7 @@ struct ExistingMessage {
cc_addrs: Vec<String>,
subject: Option<String>,
raw_blob_ref: Option<String>,
spam_score: Option<f32>,
text_body: Option<String>,
html_body: Option<String>,
}
@@ -387,7 +417,7 @@ pub async fn run_on_existing(
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 \
m.raw_blob_ref, m.spam_score, 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 \
@@ -428,6 +458,12 @@ pub async fn run_on_existing(
.clone()
.or_else(|| m.html_body.clone())
.unwrap_or_default(),
// Stored at ingest; mail from before spam scores were
// extracted has none, so fall back to its re-parsed headers.
spam_score: m
.spam_score
.map(f64::from)
.or_else(|| crate::spam::extract_score(&headers)),
headers,
};
if rule.matches(&facts) {
@@ -504,11 +540,16 @@ pub async fn apply_actions(
.execute(&mut **tx)
.await?;
}
Action::Archive => {
let archive = archive_folder(tx, user_id).await?;
Action::Archive | Action::Junk => {
let which = if *action == Action::Junk {
SystemFolder::Junk
} else {
SystemFolder::Archive
};
let folder = system_folder(tx, user_id, which).await?;
sqlx::query("UPDATE messages SET folder_id = $2 WHERE id = ANY($1)")
.bind(message_ids)
.bind(archive)
.bind(folder)
.execute(&mut **tx)
.await?;
}
@@ -544,30 +585,68 @@ pub async fn apply_actions(
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(
#[derive(Clone, Copy)]
pub enum SystemFolder {
Archive,
Junk,
}
impl SystemFolder {
fn role(self) -> &'static str {
match self {
SystemFolder::Archive => "archive",
SystemFolder::Junk => "junk",
}
}
fn default_name(self) -> &'static str {
match self {
SystemFolder::Archive => "Archive",
SystemFolder::Junk => "Junk",
}
}
}
/// A system folder (Archive, Junk), created on first use. A plain folder
/// the user happened to give the same name is adopted rather than colliding
/// with it — but never one that's already a *different* system folder,
/// which would otherwise let "Junk" steal the role of an Archive folder the
/// user had renamed to "Junk".
pub async fn system_folder(
tx: &mut Transaction<'_, Postgres>,
user_id: Uuid,
which: SystemFolder,
) -> 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?
if let Some(id) =
sqlx::query_scalar::<_, Uuid>("SELECT id FROM folders WHERE user_id = $1 AND role = $2")
.bind(user_id)
.bind(which.role())
.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' \
let adopted: Option<Uuid> = sqlx::query_scalar(
"INSERT INTO folders (user_id, name, role) VALUES ($1, $2, $3) \
ON CONFLICT (user_id, name) DO UPDATE SET role = EXCLUDED.role WHERE folders.role IS NULL \
RETURNING id",
)
.bind(user_id)
.fetch_one(&mut **tx)
.bind(which.default_name())
.bind(which.role())
.fetch_optional(&mut **tx)
.await?;
Ok(id)
if let Some(id) = adopted {
return Ok(id);
}
// The name belongs to another system folder: take a distinct one.
sqlx::query_scalar(
"INSERT INTO folders (user_id, name, role) VALUES ($1, $2 || ' (' || $3 || ')', $3) RETURNING id",
)
.bind(user_id)
.bind(which.default_name())
.bind(which.role())
.fetch_one(&mut **tx)
.await
}
/// Whether every tag and folder an action list references belongs to the
@@ -612,6 +691,7 @@ mod tests {
("received".into(), "from a".into()),
("received".into(), "from relay.example.net".into()),
],
spam_score: None,
}
}
@@ -800,6 +880,50 @@ mod tests {
assert_eq!(serde_json::from_str::<Vec<Action>>(&json).unwrap(), a);
}
fn spam(op: Op, value: &str) -> Test {
Test {
field: Field::SpamScore,
header: None,
op,
value: value.into(),
negate: false,
}
}
#[test]
fn spam_score_compares_numerically() {
// facts() carries PMG-less headers: X-Spam-Score 5.3 and a
// SpamAssassin status of 7.25; extract_score prefers the bare score.
let mut f = facts();
f.spam_score = crate::spam::extract_score(&f.headers);
assert_eq!(f.spam_score, Some(5.3));
assert!(rule(Match::All, vec![spam(Op::GreaterThan, "5")]).matches(&f));
assert!(!rule(Match::All, vec![spam(Op::GreaterThan, "6")]).matches(&f));
assert!(rule(Match::All, vec![spam(Op::Exists, "")]).matches(&f));
}
#[test]
fn unscored_mail_is_neither_over_nor_under_a_threshold() {
let mut f = facts();
f.spam_score = None;
assert!(!rule(Match::All, vec![spam(Op::GreaterThan, "0")]).matches(&f));
assert!(!rule(Match::All, vec![spam(Op::LessThan, "100")]).matches(&f));
assert!(!rule(Match::All, vec![spam(Op::Exists, "")]).matches(&f));
}
#[test]
fn spam_score_rejects_text_comparisons() {
let bad = validate(
&Conditions {
match_: Match::All,
tests: vec![spam(Op::Contains, "5")],
},
&[Action::Junk],
true,
);
assert!(bad.is_err());
}
#[test]
fn stop_is_no_longer_an_action() {
// It's a rule option now (stop_after_match). A submitted
+134
View File
@@ -0,0 +1,134 @@
//! Spam score extraction from filter headers (server-architecture-spec.md
//! §3.5, build-order phase 6).
//!
//! Proxmox Mail Gateway runs SpamAssassin and reports through headers whose
//! names are configurable, so this recognises the formats actually seen in
//! the wild rather than one fixed header:
//!
//! - PMG's `X-SPAM-LEVEL: Spam detection results: 8` — folded across lines,
//! with each matching rule and its score listed after the total.
//! - `X-Spam-Score: 5.3` — a bare number.
//! - `X-Spam-Status: Yes, score=7.2 required=5.0 …` — SpamAssassin's status.
//! - `X-Spam-Level: *******` — SpamAssassin's star bar, one per point.
//!
//! Note the name collision: PMG and SpamAssassin both use X-Spam-Level (header
//! names are case-insensitive), for completely different formats. Taking
//! "the first number in the header" would work for PMG and read nothing
//! from the star bar, so each format is matched explicitly.
//!
//! PMG only adds its header from spam level 3 upwards by default, so mail
//! below that has no score — `None`, meaning "not flagged", not "zero".
use regex::Regex;
use std::sync::LazyLock;
static PMG_RESULTS: LazyLock<Regex> =
LazyLock::new(|| Regex::new(r"(?i)spam detection results:\s*(-?\d+(?:\.\d+)?)").unwrap());
static STATUS_SCORE: LazyLock<Regex> =
LazyLock::new(|| Regex::new(r"(?i)\bscore=(-?\d+(?:\.\d+)?)").unwrap());
static BARE_NUMBER: LazyLock<Regex> =
LazyLock::new(|| Regex::new(r"^\s*(-?\d+(?:\.\d+)?)\s*$").unwrap());
fn values_of<'a>(headers: &'a [(String, String)], name: &'a str) -> impl Iterator<Item = &'a str> {
headers
.iter()
.filter(move |(n, _)| n == name)
.map(|(_, v)| v.as_str())
}
/// The message's spam score, from the most specific header present.
/// `headers` are (lowercased name, unfolded value) pairs.
pub fn extract_score(headers: &[(String, String)]) -> Option<f64> {
let values = |name: &'static str| values_of(headers, name);
// PMG's detailed result, the one this deployment is built around.
for v in values("x-spam-level") {
if let Some(c) = PMG_RESULTS.captures(v) {
return c[1].parse().ok();
}
}
for v in values("x-spam-score") {
if let Some(c) = BARE_NUMBER.captures(v) {
return c[1].parse().ok();
}
}
for v in values("x-spam-status") {
if let Some(c) = STATUS_SCORE.captures(v) {
return c[1].parse().ok();
}
}
// SpamAssassin's star bar is the least precise (whole points, floored),
// so it's the last resort.
for v in values("x-spam-level") {
let v = v.trim();
if !v.is_empty() && v.chars().all(|c| c == '*') {
return Some(v.len() as f64);
}
}
None
}
#[cfg(test)]
mod tests {
use super::*;
fn h(pairs: &[(&str, &str)]) -> Vec<(String, String)> {
pairs
.iter()
.map(|(n, v)| (n.to_string(), v.to_string()))
.collect()
}
#[test]
fn pmg_detection_results_take_the_total_not_a_rule_score() {
// As unfolded by the parser: total first, then per-rule scores —
// including negative ones that must not be mistaken for the total.
let pmg = "Spam detection results: 8 DKIM_SIGNED 0.1 Message has a DKIM or DK signature, not necessarily valid DKIM_VALID -0.1 Message has at least one valid DKIM or DK signature";
assert_eq!(extract_score(&h(&[("x-spam-level", pmg)])), Some(8.0));
assert_eq!(
extract_score(&h(&[("x-spam-level", "Spam detection results: -1.5")])),
Some(-1.5)
);
}
#[test]
fn spamassassin_star_bar_counts_stars() {
assert_eq!(extract_score(&h(&[("x-spam-level", "*******")])), Some(7.0));
}
#[test]
fn bare_score_and_status_formats() {
assert_eq!(extract_score(&h(&[("x-spam-score", "5.3")])), Some(5.3));
assert_eq!(
extract_score(&h(&[(
"x-spam-status",
"Yes, score=7.25 required=5.0 tests=BAYES_99"
)])),
Some(7.25)
);
assert_eq!(
extract_score(&h(&[("x-spam-status", "No, score=1.41")])),
Some(1.41)
);
}
#[test]
fn pmg_wins_over_less_precise_headers() {
let both = h(&[
("x-spam-level", "****"),
("x-spam-status", "Yes, score=4.9"),
("x-spam-level", "Spam detection results: 6"),
]);
assert_eq!(extract_score(&both), Some(6.0));
}
#[test]
fn unflagged_mail_has_no_score_rather_than_zero() {
assert_eq!(
extract_score(&h(&[("subject", "hi"), ("x-spam-flag", "NO")])),
None
);
// Not a star bar, not a number: ignored rather than guessed at.
assert_eq!(extract_score(&h(&[("x-spam-score", "high")])), None);
}
}