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-inbound

Scribase Mail's own MX: a tokio SMTP server that receives bounces, complaints, DMARC and TLS reports for our sending domains, plus ordinary inbound mail for domains that opt in.

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

What it does

  • Listener: configurable bind address (INBOUND_LISTEN, 25 in prod), global and per-IP connection caps, per-IP connection rate limit (421 when exceeded), per-command and DATA timeouts, error-count cutoff.
  • SMTP: EHLO/HELO, PIPELINING, SIZE (checked on MAIL FROM SIZE= and on the body), 8BITMIME, SMTPUTF8, ENHANCEDSTATUSCODES, STARTTLS from PEM files (INBOUND_TLS_CERT/INBOUND_TLS_KEY, rustls ring provider), RSET, NOOP, VRFY (252), QUIT. Command parsing and dot-unstuffing via smtp-proto.
  • Never an open relay: recipients whose domain is not in INBOUND_DOMAINS get 550 5.7.1 Relaying denied; unknown local parts on our domains get 550 5.1.1. postmaster@ and abuse@ always work.
  • Greylisting: optional (INBOUND_GREYLIST=1, off by default), first attempt per (ip, sender, recipient) answers 450 for INBOUND_GREYLIST_DELAY_SECS.
  • Authentication: SPF (HELO + MAIL FROM), DKIM, ARC and DMARC via the mail-auth library; an Authentication-Results: header and a Received: trace header are prepended to the stored message.
  • Routing by recipient
    • bounces+<id>@…: RFC 3464 DSN parsing (message/delivery-status, per-recipient Action/Status/Diagnostic-Code) → InboundSink::bounce(id, hard, detail); hard = failed with a 5.x.x status. Non-RFC 3464 bounces are classified from the text.
    • ARF (RFC 5965, report-type=feedback-report) on any address → InboundSink::complaint(id, detail); the id is recovered from VERP in Original-Mail-From, the embedded Return-Path, or X-Mail-Id.
    • dmarc@…: aggregate XML in zip/gzip/plain attachments → parsed and stored with per-row auth results; per-domain/day pass/fail rolled up in inb_dmarc_domain_stats.
    • tls-rpt@…: RFC 8460 JSON (optionally gzip) → inb_tlsrpt_reports.
    • Anything else on an INBOUND_RECEIVE_DOMAINS domain → stored (Postgres inb_messages or a directory) and delivered to InboundSink::received.
  • Sink: InboundSink { bounce, complaint, received } trait; LoggingSink for development. mail-server (src/inbound.rs, CoreInboundSink) wires it to mail_core::record_inbound_event: hard DSN → bounced + suppression, Action: delayed → delivery_delayed, ARF → complained + suppression, each firing the account's webhooks. The ingest runs inside mail-server when INBOUND_HTTP_SECRET is set.
  • Storage: DATABASE_URL → Postgres (inb_* tables, migrations in migrations/, tracked in this crate's own _inb_migrations table), or INBOUND_STORE_DIR → files, or neither (sink only).
  • Dev DNS overrides: INBOUND_DNS_OVERRIDES_FILE seeds mail-auth's TXT cache with name TXT value lines so a throwaway domain's DKIM key, SPF and DMARC records resolve locally.

HTTPS ingest — inbound without port 25 (production shape)

Owner decision 2026-11-13: we never listen on 25. Cloudflare Email Routing is the MX for bounce.scribase.com, inbound.scribase.com, dmarc@ / tls-rpt@ / postmaster@ / abuse@scribase.com; its Email Worker (apps/mail/workers/inbound-forwarder) POSTs each raw message to POST /inbound/raw here. The body then goes through the same Processor::handle as an SMTP DATA: same Authentication-Results and Received trace headers, same routing (bounces+<id>@ → DSN → InboundSink::bounce, ARF → InboundSink::complaint, dmarc@ → aggregate report, tls-rpt@ → TLS-RPT, mailbox → stored + InboundSink::received), same storage.

  • Auth: X-Scribase-Timestamp (unix seconds, ±INBOUND_HTTP_MAX_SKEW_SECS, default 300), X-Scribase-Envelope-From, X-Scribase-Envelope-To, X-Scribase-Signature: v1=<hex HMAC-SHA256(secret, "v1\n{ts}\n{from}\n{to}\n{sha256hex(body)}")>. Constant-time compare; a signature is single-use for INBOUND_HTTP_REPLAY_WINDOW_SECS (900).
  • Replies: 202 {accepted,id,kind}; 401 unauthorized (bad/missing/stale/replayed signature); 403 relay_denied (not our domain); 404 unknown_recipient; 413 too_large; 422 bad_recipient_syntax; 500 processing_failed (storage; the Worker makes the sender retry). The Worker turns 403/404/413/422 into permanent SMTP rejections and anything else into a temporary one.
  • SPF: we are not the connecting MX, so SPF is none unless the Worker sends X-Scribase-Remote-Ip; DKIM/ARC/DMARC run normally (DMARC on DKIM alone).
  • Wiring: InboundServer::http_ingest(IngestConfig) shares the running MX's processor/storage; HttpIngest::bind_standalone(inbound_cfg, ingest_cfg, sink) runs HTTP only (no SMTP socket at all) — the production mode.
Variable Default Meaning
INBOUND_HTTP_LISTEN 127.0.0.1:8585 Bind address (put TLS termination in front).
INBOUND_HTTP_SECRET required (≥ 32 chars) Same value as the Worker's INGEST_SECRET.
INBOUND_HTTP_MAX_SKEW_SECS 300 Timestamp tolerance.
INBOUND_HTTP_MAX_SIZE INBOUND_MAX_SIZE Body cap.
INBOUND_HTTP_REPLAY_WINDOW_SECS 900 Signature memory.

Verified locally 2026-11-13 (examples/serve with dir storage, examples/ingest_feed, workers/inbound-forwarder/scripts/local-check.mjs, wrangler dev + POST /cdn-cgi/handler/email): DSN / ARF / DMARC-gzip / TLS-RPT / plain bounce over HTTP → 202 and the sink logged the identical BOUNCE(abc, 5.1.1), COMPLAINT(cmp42), DMARC(123 rows, 120 pass, 3 fail) and TLS-RPT(5326 ok, 2 failed) as the SMTP feed of the same samples; stored JSON records are identical between the two paths (plain-text bounce differs by one trailing CRLF from SMTP dot-unstuffing). Bad HMAC, timestamp ±15 min, replay, missing headers → 401; victim@gmail.com → 403; nobody@reports.dev.test → 404; the Worker then rejected with 550 5.1.1 / 550 5.7.1, and a wrong secret made the handler throw (temporary failure) instead of rejecting.

Configuration (environment)

Variable Default Meaning
INBOUND_LISTEN 127.0.0.1:2525 Bind address.
INBOUND_HOSTNAME mx.<first domain> Banner / EHLO / Received name.
INBOUND_DOMAINS required Comma-separated domains we accept mail for.
INBOUND_RECEIVE_DOMAINS = INBOUND_DOMAINS Domains whose ordinary mailboxes are stored.
INBOUND_TLS_CERT, INBOUND_TLS_KEY unset PEM chain and key for STARTTLS.
INBOUND_MAX_SIZE 25 MiB Message size cap.
INBOUND_MAX_CONNECTIONS, INBOUND_MAX_CONNECTIONS_PER_IP 200 / 10 Connection caps.
INBOUND_RATE_PER_MIN 60 New connections per IP per minute.
INBOUND_MAX_RCPT, INBOUND_MAX_ERRORS 100 / 10 Per-transaction and per-session limits.
INBOUND_GREYLIST, INBOUND_GREYLIST_DELAY_SECS 0, 300 Greylisting.
INBOUND_COMMAND_TIMEOUT_SECS, INBOUND_DATA_TIMEOUT_SECS 300 / 600 Timeouts.
DATABASE_URL / INBOUND_STORE_DIR unset Storage backend.
INBOUND_DNS_OVERRIDES_FILE unset Dev TXT overrides.
INBOUND_BOUNCE_PREFIX, INBOUND_DMARC_LOCAL, INBOUND_TLSRPT_LOCAL bounces, dmarc, tls-rpt Special local parts.

Running it locally

createdb mail_dev_mta
DATABASE_URL=postgres://$USER@localhost/mail_dev_mta INBOUND_DOMAINS=dev.test,reports.dev.test \
INBOUND_RECEIVE_DOMAINS=dev.test INBOUND_DEV_SELF_SIGNED=1 \
INBOUND_DNS_OVERRIDES_FILE=/tmp/scribase-mail-dev/dns-overrides.txt \
cargo run -p mail-inbound --example serve

# in another shell:
cargo run -p mail-inbound --example feed        # DSN, ARF, DMARC gzip, TLS-RPT, relay + unknown-user rejections
cargo run -p mail-mta --example send_local      # DKIM-signed delivery over STARTTLS from DirectTransport

Dependencies and licences

Crate Licence
tokio, tokio-rustls, sqlx, chrono, flate2, tracing, uuid, serde, serde_json, thiserror, async-trait MIT OR Apache-2.0
rustls, rustls-pki-types, rustls-pemfile Apache-2.0 OR ISC OR MIT
mail-auth (as mail-auth-lib, features rust-crypto, dns-hickory, arc), mail-parser, smtp-proto Apache-2.0 OR MIT
zip, quick-xml MIT
rcgen (dev-dependency) MIT OR Apache-2.0

No AGPL code or dependency is involved; mail-auth's default aws-lc-rs feature is disabled in favour of pure-Rust crypto.

Known gaps

  • No PTR/iprev check yet (mail-auth supports it; add once prod has a PTR).
  • CHUNKING/BDAT and AUTH are refused (502/503); this is an MX, not a submission server.
  • Greylist state is in memory only.