caelum0x 219a58e855 feat(mail): wire one mail-server process — relay pool default, SMTP submit, Supabase hook, inbound ingest, OCI onboarding
- mail-server spawns SMTP submission + HTTPS inbound ingest, mounts Supabase hook router
- RelayPool is the default transport; relay rejections mark email failed without suppressing recipient
- inbound DSN/ARF -> bounced/complained + suppression + webhooks
- domains API returns Resend-style records incl. OCI DKIM; OCI onboarding gated by OCI_ONBOARDING=on
- OCI suppression mirror sync; docs: test mode uses sk_test_

Verified end to end locally against a fake relay (API + SMTP send, DKIM valid, bounce -> suppressed -> 403, complaint, Supabase hook, 7 signed webhooks).

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-13 01:42:48 +03:00
..

mail-mta

Scribase Mail's outbound MTA: delivers fully signed RFC 5322 messages straight to recipient MX hosts. Implements the Transport trait from mail-types, so mail-core can switch between the OCI smarthost relay and direct delivery the moment outbound port 25 opens.

Independent implementation, written without reference to useSend or Stalwart server source. Licence: MIT (workspace).

What it does

  • MX resolution via hickory: MX preference order, implicit MX (A/AAAA fallback, RFC 5321 §5.1), null MX (RFC 7505 → 556 5.1.10), NXDOMAIN → 550 5.1.2, temporary DNS trouble → 451 4.4.3. Dev override MTA_MX_OVERRIDE pins a domain to fixed host:port addresses.
  • SMTP client: configurable EHLO hostname, HELO fallback, bound source IP (MTA_SOURCE_IP), per-phase timeouts from RFC 5321 §4.5.3.2, multi-line reply parsing with enhanced status codes (RFC 3463), classification 2xx → Delivered, 4xx/timeouts/connect failures → Deferred, 5xx → Bounced.
  • STARTTLS with rustls (ring provider). Opportunistic by default (encrypt-only verifier, cleartext retry on handshake failure, RFC 7435); MTA_REQUIRE_TLS=1 forbids cleartext.
  • MTA-STS (RFC 8461): _mta-sts TXT discovery, HTTPS policy fetch over our own tokio-rustls HTTP/1.1 client (no redirects, 64 KiB cap), cache keyed by id/max_age, MX pattern matching incl. *. wildcards; enforce requires WebPKI-valid certificates for the MX hostname and skips non-matching MX hosts.
  • DANE (RFC 7672, opt-in MTA_DANE=1 + MTA_DNSSEC=1): TLSA lookup used only when MX and TLSA answers are DNSSEC-secure; DANE-EE/DANE-TA with Cert/SPKI selectors and Full/SHA-256/SHA-512 matching; PKIX-EE/PKIX-TA also run WebPKI. DANE wins over MTA-STS when usable.
  • Extensions: PIPELINING (MAIL/RCPT/DATA in one write, replies read in order), SIZE (pre-flight check, SIZE= parameter), 8BITMIME (BODY=8BITMIME when the body has 8-bit bytes), SMTPUTF8 (required when any address is non-ASCII; otherwise 553 5.6.7), CRLF normalisation and dot-stuffing.
  • Throttling: per-destination-domain connection semaphores, send pacing and hourly caps from provider profiles (gmail, outlook, yahoo, default), selected by recipient domain or MX hostname suffix (hosted mailboxes), all overridable with MTA_PROFILE_<NAME>=key=value,..., MTA_PROFILE_<NAME>_DOMAINS, MTA_PROFILE_<NAME>_MX_SUFFIXES.
  • Connection reuse: idle sessions pooled per domain, bounded by the profile's max_messages_per_connection and MTA_IDLE_TTL_SECS.
  • IP warm-up (MTA_WARMUP=1): per-sending-IP daily caps ramping along MTA_WARMUP_SCHEDULE (default 50 → 300 000 over 14 days), state in Postgres tables mta_warmup_ips / mta_warmup_daily (migrations in migrations/, tracked in this crate's own _mta_migrations table so they coexist with other crates' migrations in one database). Over-cap sends defer with 451 4.7.1; deferred sends give their quota back.
  • TLS-RPT (RFC 8460): aggregates successes and failure classes per destination domain and policy (sts, tlsa, no-policy-found), persists failures to mta_tls_failures, and prepare_reports() builds the JSON report, gzips it, stores it in mta_tls_reports and returns it with the domain's rua targets. Sending the report through the normal queue is the caller's job (stub boundary).

RelayPool — the transport we actually run (no port 25 anywhere)

Owner decision 2026-11-13: no host will ever allow outbound 25, so mail_mta::relay::RelayPool is the production mail_types::Transport. DirectTransport stays code-complete but unused.

  • N authenticated submission relays in priority order. Primary = OCI Email Delivery (smtp.email.<OCI_REGION>.oci.oraclecloud.com:587, STARTTLS, AUTH PLAIN/LOGIN; SMTP_HOST/PORT/USER/PASS still work as the primary's fallback). Secondary slot is generic SMTP and off by default; for Cloudflare Email Sending it is smtp.mx.cloudflare.net:465, implicit TLS, user api_token, password = an API token with Email Sending: Edit. Honest limits of that option: the From domain must be on our Cloudflare account's DNS and onboarded there, so it can only carry our own domains, never a customer's; arbitrary recipients need Workers Paid (3 000/month included, then $0.35 per 1 000). That is owner spend, so it stays RELAY_SECONDARY_HOST-unset until decided.
  • Failover on connect / TLS / AUTH / greeting / EHLO failure, on 4xx from the relay at MAIL FROM or DATA (busy, throttled, quota), and when the relay refuses the whole message (so a sender OCI has not approved can still go through a relay that owns the domain). Never on a recipient-level reply (RCPT TO 5xx stays a bounce for that recipient) and never after the final . was sent (connection lost there → 451 4.4.2 deferred, no duplicate risk).
  • Clear relay rejections: a 5xx at MAIL FROM / DATA / end-of-data yields, for every recipient, code = the relay's code, outcome = Deferred, and message = "[relay-rejected] <relay> <phase>: sender not approved on relay (add it as an approved sender) — <relay text>" (RELAY_REJECTED_PREFIX, is_relay_rejection()), so it is never recorded as a recipient hard bounce or suppression. OCI's "not approved" wording, size limits and content rejections are recognised (RejectKind).
  • Health: exponential back-off per relay (30 s → 10 min), a 5 s loop that re-probes relays in back-off plus a full probe every RELAY_HEALTH_INTERVAL_SECS, RelayPool::health() for a status page (sent_today, daily_quota, last_error, backoff_remaining_secs).
  • Quotas: per-relay daily counter (UTC day) reserved before each attempt and released on failure; OCI default RELAY_PRIMARY_DAILY_QUOTA=50000 (its max-emails-day) and RELAY_PRIMARY_MAX_MESSAGE_SIZE=2008192 (its max-message-size), both read from the real tenancy via mail-oci. A relay that answers "quota exceeded" is skipped for an hour.
Variable Default Meaning
RELAY_PRIMARY_HOST/PORT/TLS/USER/PASS/NAME OCI in OCI_REGION, 587, starttls, SMTP_USER/PASS, oci Primary relay. TLS ∈ implicit, starttls, none (loopback only).
RELAY_PRIMARY_DAILY_QUOTA, RELAY_PRIMARY_MAX_MESSAGE_SIZE 50000 / 2008192 for oci Per-day recipients, max bytes.
RELAY_SECONDARY_*, RELAY_TERTIARY_* unset = disabled Same keys; secondary defaults 465/implicit/cloudflare.
RELAY_EHLO_HOSTNAME MTA_EHLO_HOSTNAME or mail.scribase.com EHLO name.
RELAY_HEALTH_INTERVAL_SECS, RELAY_FAILURE_BACKOFF_SECS, RELAY_MAX_BACKOFF_SECS 60 / 30 / 600 Probe cadence and back-off.
RELAY_DEV_TRUST_ANY 0 Accept any certificate (local sinks).

Verified locally 2026-11-13 against two Python SMTP sinks with AUTH (cargo run -p mail-mta --example relay_demo): quota 3 on primary → messages 4-5 via secondary with quota_exhausted=true in health; primary killed mid-run → messages 2-6 via secondary, back-off 3 s → 6 s, health healthy=false, last_error="Connection refused"; recipient 550 5.1.1 on primary stays Bounced, no failover; MAIL FROM 554 Sender address not approved → secondary takes it, or with primary only → 554 5.7.1 Deferred "[relay-rejected] oci MAIL FROM: sender not approved…"; same for a header-From rejection at end-of-data; wrong AUTH password → probe fails, traffic goes to secondary.

Wired (2026-11-13). RELAY_REJECTED_PREFIX now lives in mail-types (RecipientResult::is_relay_rejection(), re-exported here); mail-core's Worker marks such emails failed with the relay's text, no retry and no recipient suppression (email.failed webhook carries the reason). mail-server builds the pool for MAIL_TRANSPORT=relay-pool (the default, src/transport.rs), runs probe_all() at start-up, spawns spawn_health_checks() and returns pool.health() in GET /healthz.

Configuration (environment)

Variable Default Meaning
MTA_EHLO_HOSTNAME required Name sent in EHLO; must match the PTR of the sending IP in production.
MTA_SOURCE_IP unset Bind outgoing connections to this IP. Required for warm-up.
MTA_TLS_DEV_TRUST_ANY 0 Dev only: accept any certificate.
MTA_REQUIRE_TLS 0 Never deliver in cleartext.
MTA_STS 1 Enable MTA-STS.
MTA_DANE, MTA_DNSSEC 0 Enable DANE (needs a validating resolver path).
MTA_MX_OVERRIDE unset `domain=host:port[
MTA_PROFILE_<NAME> built-in max_connections=,max_messages_per_connection=,max_rcpt=,min_interval_ms=,max_per_hour=
MTA_IDLE_TTL_SECS 60 Idle pooled connection lifetime.
MTA_MAX_MESSAGE_SIZE 50 MiB Our own hard cap.
DATABASE_URL unset Postgres for warm-up and TLS-RPT persistence.
MTA_WARMUP, MTA_WARMUP_SCHEDULE 0, built-in Warm-up on/off and daily caps.
MTA_TLSRPT_ORG, MTA_TLSRPT_CONTACT Scribase Mail Report metadata.
MTA_CONNECT_TIMEOUT_SECS, MTA_GREETING_TIMEOUT_SECS, MTA_DATA_TERM_TIMEOUT_SECS 30 / 300 / 600 Timeout overrides.

Running it locally

# 1. start the local MX (see crates/mail-inbound/README.md), then:
cargo run -p mail-mta --example send_local        # first run writes the dev DKIM key + DNS overrides, restart inbound, run again
cargo run -p mail-mta --example mx_lookup -- gmail.com   # real DNS + MTA-STS fetch, no port 25

Note: the Oracle boxes currently have outbound TCP 25 blocked and no PTR record. Direct delivery to the public internet cannot be exercised from there until an egress exception exists; everything here is verified against the local mail-inbound MX and real DNS/HTTPS only.

Dependencies and licences

Crate Licence
tokio, tokio-rustls, hickory-resolver, rustls-native-certs, sqlx, chrono, tracing, sha2, x509-parser, flate2, serde, serde_json, thiserror, async-trait MIT OR Apache-2.0
rustls, rustls-pki-types Apache-2.0 OR ISC OR MIT
mail-auth (dev-dependency, as mail-auth-lib), mail-builder (dev-dependency) Apache-2.0 OR MIT

Root certificates come from the operating system store (rustls-native-certs), not from a bundled webpki-roots crate.

Known gaps

  • No live test against Gmail/Outlook yet (port 25 blocked from prod).
  • TLS-RPT reports are prepared, not mailed; mail-core wires prepare_reports() into its queue.
  • CHUNKING/BDAT is detected but not used; DATA is always used.
  • Warm-up caps are per IP, not per provider.