diff --git a/apps/mail/Cargo.lock b/apps/mail/Cargo.lock index 701523c5..cba340f5 100644 --- a/apps/mail/Cargo.lock +++ b/apps/mail/Cargo.lock @@ -1725,7 +1725,6 @@ name = "mail-hooks" version = "0.1.0" dependencies = [ "anyhow", - "async-trait", "axum", "base64 0.22.1", "hmac 0.12.1", @@ -1841,11 +1840,18 @@ name = "mail-server" version = "0.1.0" dependencies = [ "anyhow", + "async-trait", "axum", "base64 0.22.1", + "chrono", "ed25519-dalek 2.2.0", "mail-auth 0.1.0", "mail-core", + "mail-hooks", + "mail-inbound", + "mail-mta", + "mail-oci", + "mail-submit", "mail-types", "reqwest", "serde", @@ -1868,7 +1874,6 @@ dependencies = [ "anyhow", "base64 0.22.1", "mail-core", - "mail-parser", "mail-types", "rustls", "rustls-pemfile", diff --git a/apps/mail/crates/mail-core/src/dns.rs b/apps/mail/crates/mail-core/src/dns.rs index a5fa3697..7daeab80 100644 --- a/apps/mail/crates/mail-core/src/dns.rs +++ b/apps/mail/crates/mail-core/src/dns.rs @@ -1,17 +1,65 @@ //! The DNS records a sending domain must publish, and their real verification //! through the system resolver (hickory). -use hickory_resolver::proto::rr::RData; +use hickory_resolver::proto::rr::{RData, RecordType}; use hickory_resolver::{Resolver, TokioResolver}; use crate::config::CoreConfig; use crate::error::{CoreError, Result}; use crate::model::{DnsRecord, Domain}; -const STATUS_NOT_STARTED: &str = "not_started"; -const STATUS_VERIFIED: &str = "verified"; -const STATUS_FAILED: &str = "failed"; -const STATUS_PENDING: &str = "pending"; +pub const STATUS_NOT_STARTED: &str = "not_started"; +pub const STATUS_VERIFIED: &str = "verified"; +pub const STATUS_FAILED: &str = "failed"; +pub const STATUS_PENDING: &str = "pending"; + +/// Record name meaning "the domain itself" (Resend shows the bare domain; +/// we use the conventional `@`). +pub const APEX: &str = "@"; + +/// Build a `DnsRecord` in the `not_started` state. +pub fn record( + kind: &str, + name: &str, + rtype: &str, + value: String, + priority: Option, + purpose: Option<&str>, +) -> DnsRecord { + DnsRecord { + record: kind.into(), + name: name.into(), + record_type: rtype.into(), + ttl: "Auto".into(), + status: STATUS_NOT_STARTED.into(), + value, + priority, + purpose: purpose.map(str::to_owned), + } +} + +/// Turn a fully qualified owner name into the relative form we store +/// (`scribase._domainkey.example.com` → `scribase._domainkey`, apex → `@`). +pub fn relative_name(fqdn: &str, domain: &str) -> String { + let owner = fqdn.trim_end_matches('.').to_ascii_lowercase(); + let domain = domain.trim_end_matches('.').to_ascii_lowercase(); + if owner == domain { + return APEX.into(); + } + owner + .strip_suffix(&format!(".{domain}")) + .map(str::to_owned) + .unwrap_or(owner) +} + +/// Absolute owner name (trailing dot) for a stored record. +fn fqdn(record_name: &str, domain: &str) -> String { + if record_name.is_empty() || record_name == APEX { + format!("{domain}.") + } else { + format!("{record_name}.{domain}.") + } +} /// Records for a new domain, all `not_started`. pub fn initial_records( @@ -20,16 +68,9 @@ pub fn initial_records( selector: &str, public_key_b64: &str, ) -> Vec { - let rec = - |record: &str, name: &str, rtype: &str, value: String, priority: Option| DnsRecord { - record: record.into(), - name: name.into(), - record_type: rtype.into(), - ttl: "Auto".into(), - status: STATUS_NOT_STARTED.into(), - value, - priority, - }; + let rec = |kind: &str, name: &str, rtype: &str, value: String, priority: Option| { + record(kind, name, rtype, value, priority, None) + }; let mut records = vec![rec( "DKIM", &format!("{selector}._domainkey"), @@ -67,10 +108,11 @@ pub async fn verify_domain(domain: &Domain) -> Result { let mut records = domain.records.0.clone(); for record in &mut records { - let fqdn = format!("{}.{}.", record.name, domain.name); + let fqdn = fqdn(&record.name, &domain.name); let ok = match record.record_type.as_str() { "TXT" => txt_matches(&resolver, &fqdn, record).await?, "MX" => mx_matches(&resolver, &fqdn, &record.value).await?, + "CNAME" => cname_matches(&resolver, &fqdn, &record.value).await?, _ => false, }; record.status = if ok { STATUS_VERIFIED } else { STATUS_FAILED }.into(); @@ -128,13 +170,46 @@ async fn txt_matches(resolver: &TokioResolver, fqdn: &str, record: &DnsRecord) - } "SPF" => { let want = squash(&record.value); - found.iter().any(|v| squash(v) == want) + found.iter().any(|v| spf_satisfies(&squash(v), &want)) } "DMARC" => found.iter().any(|v| squash(v).starts_with("v=dmarc1")), _ => false, }) } +/// A published SPF record satisfies ours when it is identical, or when it is +/// a valid `v=spf1` record that carries every `include:` we asked for (the +/// customer merged our include into an existing record, which is what we +/// tell them to do). +fn spf_satisfies(published: &str, wanted: &str) -> bool { + if published == wanted { + return true; + } + if !published.starts_with("v=spf1") { + return false; + } + let includes: Vec<&str> = wanted + .split([' ', '~', '-', '?', '+']) + .filter(|tok| tok.starts_with("include:")) + .collect(); + !includes.is_empty() && includes.iter().all(|inc| published.contains(inc)) +} + +async fn cname_matches(resolver: &TokioResolver, fqdn: &str, target: &str) -> Result { + let want = target.trim_end_matches('.').to_ascii_lowercase(); + match resolver.lookup(fqdn, RecordType::CNAME).await { + Ok(lookup) => Ok(lookup.answers().iter().any(|r| match &r.data { + RData::CNAME(c) => c + .to_utf8() + .trim_end_matches('.') + .eq_ignore_ascii_case(&want), + _ => false, + })), + Err(e) if e.is_no_records_found() => Ok(false), + Err(e) => Err(CoreError::Dns(format!("{fqdn}: {e}"))), + } +} + async fn mx_matches(resolver: &TokioResolver, fqdn: &str, host: &str) -> Result { let want = host.trim_end_matches('.').to_ascii_lowercase(); match resolver.mx_lookup(fqdn).await { diff --git a/apps/mail/crates/mail-core/src/events.rs b/apps/mail/crates/mail-core/src/events.rs index 45adc5f0..2d2e6b5d 100644 --- a/apps/mail/crates/mail-core/src/events.rs +++ b/apps/mail/crates/mail-core/src/events.rs @@ -74,6 +74,9 @@ pub enum InboundEventKind { Bounce, Complaint, Delivered, + /// Soft bounce / delay notice (DSN `Action: delayed`, 4.x.x): the remote + /// side keeps retrying, so nothing is suppressed. + Delayed, } impl InboundEventKind { @@ -82,6 +85,7 @@ impl InboundEventKind { "bounce" | "bounced" => Some(Self::Bounce), "complaint" | "complained" => Some(Self::Complaint), "delivered" | "delivery" => Some(Self::Delivered), + "delayed" | "delivery_delayed" | "soft_bounce" => Some(Self::Delayed), _ => None, } } @@ -126,6 +130,11 @@ pub async fn record_inbound_event( Some("complaint"), ), InboundEventKind::Delivered => (EmailStatus::Delivered, "email.delivered", None), + InboundEventKind::Delayed => ( + EmailStatus::DeliveryDelayed, + "email.delivery_delayed", + None, + ), }; // Test-mode sends never touch the suppression lists. if let (Some(reason), false) = (reason, email.test) { @@ -152,6 +161,9 @@ pub async fn record_inbound_event( InboundEventKind::Delivered => { json!({ "delivery": { "message": detail.message, "recipients": targets } }) } + InboundEventKind::Delayed => { + json!({ "delayed": { "message": detail.message, "code": detail.code, "recipients": targets } }) + } }; emit(&store, &email, event_type, extra).await } diff --git a/apps/mail/crates/mail-core/src/model.rs b/apps/mail/crates/mail-core/src/model.rs index 01ad1195..1ad5907a 100644 --- a/apps/mail/crates/mail-core/src/model.rs +++ b/apps/mail/crates/mail-core/src/model.rs @@ -148,6 +148,9 @@ pub struct DnsRecord { pub value: String, #[serde(default, skip_serializing_if = "Option::is_none")] pub priority: Option, + /// What the record is for, in plain words (shown next to the record). + #[serde(default, skip_serializing_if = "Option::is_none")] + pub purpose: Option, } #[derive(Debug, Clone, sqlx::FromRow)] diff --git a/apps/mail/crates/mail-core/src/raw.rs b/apps/mail/crates/mail-core/src/raw.rs index 04288f8d..a7fdf66e 100644 --- a/apps/mail/crates/mail-core/src/raw.rs +++ b/apps/mail/crates/mail-core/src/raw.rs @@ -10,7 +10,7 @@ use crate::address::{normalize, Mailbox}; use crate::config::CoreConfig; use crate::enqueue::{check_account, Caller}; use crate::error::{CoreError, Result}; -use crate::model::Email; +use crate::model::{Email, Tag}; use crate::store::{NewEmailRow, PgStore}; /// Largest raw message accepted (headers + body), matching the attachment @@ -106,13 +106,15 @@ fn header_mailboxes(headers: &[(String, String)], name: &str) -> Vec { .collect() } -/// Validate and queue a finished message for `envelope_rcpts`. +/// Validate and queue a finished message for `envelope_rcpts`. `tags` are +/// recorded on the email (e.g. `source=smtp`) and show up in webhooks. pub async fn enqueue_raw( store: &PgStore, cfg: &CoreConfig, caller: &Caller, raw: &[u8], envelope_rcpts: &[String], + tags: Vec, ) -> Result { if raw.is_empty() { return Err(CoreError::validation("message is empty")); @@ -191,7 +193,7 @@ pub async fn enqueue_raw( html: None, text: None, headers: serde_json::Map::new(), - tags: Vec::new(), + tags, attachments: Vec::new(), message_id, pending_rcpts: pending, diff --git a/apps/mail/crates/mail-core/src/store/domains.rs b/apps/mail/crates/mail-core/src/store/domains.rs index 4682032e..baeefe60 100644 --- a/apps/mail/crates/mail-core/src/store/domains.rs +++ b/apps/mail/crates/mail-core/src/store/domains.rs @@ -120,6 +120,20 @@ impl PgStore { .map_err(|e| CoreError::from_sqlx("domain", e)) } + /// Replace the records to publish (e.g. after the relay control plane + /// handed us its DKIM CNAME) without touching the verification status. + pub async fn update_domain_records(&self, id: Uuid, records: &[DnsRecord]) -> Result { + let sql = format!( + "UPDATE mail_domains SET records = $2, updated_at = now() WHERE id = $1 RETURNING {COLS}" + ); + sqlx::query_as::<_, Domain>(&sql) + .bind(id) + .bind(Json(records)) + .fetch_one(&self.pool) + .await + .map_err(|e| CoreError::from_sqlx("domain", e)) + } + /// Persist a verification pass: per-record statuses and the roll-up. /// Becoming `verified` while another account already holds the name /// verified is a conflict. diff --git a/apps/mail/crates/mail-core/src/store/emails.rs b/apps/mail/crates/mail-core/src/store/emails.rs index 8dba7ae0..1f65a8f3 100644 --- a/apps/mail/crates/mail-core/src/store/emails.rs +++ b/apps/mail/crates/mail-core/src/store/emails.rs @@ -109,6 +109,22 @@ impl PgStore { .map_err(|e| CoreError::from_sqlx("email", e)) } + /// Distinct `From` addresses (bare, lowercased) ever used on a domain, so + /// the relay control plane can approve each one. + pub async fn from_addresses_for_domain(&self, domain_id: Uuid) -> Result> { + let rows: Vec<(String,)> = sqlx::query_as( + "SELECT DISTINCT from_address FROM mail_emails WHERE domain_id = $1 AND test = false", + ) + .bind(domain_id) + .fetch_all(&self.pool) + .await?; + Ok(rows + .into_iter() + .filter_map(|(f,)| crate::address::Mailbox::parse(&f).ok()) + .map(|m| m.address.to_ascii_lowercase()) + .collect()) + } + /// Newest-first keyset pagination on `(created_at, id)` within an account. pub async fn list_emails( &self, diff --git a/apps/mail/crates/mail-core/src/store/mod.rs b/apps/mail/crates/mail-core/src/store/mod.rs index fc2f1ede..db5b4e8b 100644 --- a/apps/mail/crates/mail-core/src/store/mod.rs +++ b/apps/mail/crates/mail-core/src/store/mod.rs @@ -58,6 +58,29 @@ impl PgStore { Ok(()) } + /// Read a setting if present. + pub async fn setting(&self, key: &str) -> Result> { + let row: Option<(String,)> = + sqlx::query_as("SELECT value FROM mail_settings WHERE key = $1") + .bind(key) + .fetch_optional(&self.pool) + .await?; + Ok(row.map(|(v,)| v)) + } + + /// Write (insert or replace) a setting. + pub async fn set_setting(&self, key: &str, value: &str) -> Result<()> { + sqlx::query( + "INSERT INTO mail_settings (key, value) VALUES ($1, $2) + ON CONFLICT (key) DO UPDATE SET value = EXCLUDED.value", + ) + .bind(key) + .bind(value) + .execute(&self.pool) + .await?; + Ok(()) + } + /// Read a setting, inserting `default_value()` when absent (atomic). pub async fn setting_or_init( &self, diff --git a/apps/mail/crates/mail-core/src/store/suppressions.rs b/apps/mail/crates/mail-core/src/store/suppressions.rs index 83890bac..4793c123 100644 --- a/apps/mail/crates/mail-core/src/store/suppressions.rs +++ b/apps/mail/crates/mail-core/src/store/suppressions.rs @@ -52,6 +52,28 @@ impl PgStore { Ok(()) } + /// Add an address straight to the global list (every account). Used by + /// the OCI suppression mirror: the relay sees bounces and complaints for + /// all tenants, so its entries protect everyone. Returns `true` when the + /// address was new. + pub async fn upsert_global_suppression( + &self, + address: &str, + reason: &str, + detail: Option<&str>, + ) -> Result { + let done = sqlx::query( + "INSERT INTO mail_global_suppressions (address, reason, detail) + VALUES ($1, $2, $3) ON CONFLICT (address) DO NOTHING", + ) + .bind(normalize(address)) + .bind(reason) + .bind(detail) + .execute(&self.pool) + .await?; + Ok(done.rows_affected() > 0) + } + /// Which of `addresses` are suppressed for this account (its own list or /// the global one), lowercased. pub async fn suppressed_among( diff --git a/apps/mail/crates/mail-core/src/timefmt.rs b/apps/mail/crates/mail-core/src/timefmt.rs index ec67ca8f..9e8fcd9e 100644 --- a/apps/mail/crates/mail-core/src/timefmt.rs +++ b/apps/mail/crates/mail-core/src/timefmt.rs @@ -30,6 +30,11 @@ pub fn rfc2822(t: OffsetDateTime) -> String { .unwrap_or_else(|_| t.unix_timestamp().to_string()) } +/// `Date:` header value for right now (for callers that do not depend on `time`). +pub fn now_rfc2822() -> String { + rfc2822(OffsetDateTime::now_utc()) +} + /// Parse an ISO 8601 / RFC 3339 `scheduled_at` value. Natural-language /// values ("in 1 min") are rejected with a clear message. pub fn parse_scheduled_at(raw: &str) -> Result { diff --git a/apps/mail/crates/mail-core/src/worker.rs b/apps/mail/crates/mail-core/src/worker.rs index 437afc7e..c3fd118d 100644 --- a/apps/mail/crates/mail-core/src/worker.rs +++ b/apps/mail/crates/mail-core/src/worker.rs @@ -33,6 +33,9 @@ pub(crate) struct Sorted<'a> { accepted: Vec<&'a RecipientResult>, deferred: Vec<&'a RecipientResult>, bounced: Vec<&'a RecipientResult>, + /// The relay refused the whole message (`[relay-rejected] …`): terminal + /// `failed`, never a retry, never a recipient suppression. + rejected: Vec<&'a RecipientResult>, } /// Everything a worker needs; cheap to clone. Build with [`Worker::new`]. @@ -220,6 +223,12 @@ impl Worker { final_hop: bool, ) -> Result<()> { let sorted = self.record_outcomes(email, &results).await?; + if let Some(rejected) = sorted.rejected.first() { + // The relay (not a recipient) refused the message: the sender must + // act (approve the address, shrink the message), so retrying or + // suppressing anyone would be wrong. + return self.fail(email, &rejected.message).await; + } self.handle_bounces(email, &sorted.bounced).await?; let attempts_after = email.attempts + 1; @@ -238,6 +247,10 @@ impl Worker { let mut sorted = Sorted::default(); for r in results { self.store.insert_delivery(email, r).await?; + if r.is_relay_rejection() { + sorted.rejected.push(r); + continue; + } match r.outcome { DeliveryOutcome::Delivered => sorted.accepted.push(r), DeliveryOutcome::Deferred => sorted.deferred.push(r), diff --git a/apps/mail/crates/mail-hooks/Cargo.toml b/apps/mail/crates/mail-hooks/Cargo.toml index 5a72336d..f5d66927 100644 --- a/apps/mail/crates/mail-hooks/Cargo.toml +++ b/apps/mail/crates/mail-hooks/Cargo.toml @@ -16,7 +16,6 @@ path = "src/main.rs" [dependencies] mail-core = { path = "../mail-core" } mail-types.workspace = true -async-trait.workspace = true serde.workspace = true serde_json.workspace = true thiserror.workspace = true diff --git a/apps/mail/crates/mail-hooks/README.md b/apps/mail/crates/mail-hooks/README.md index 14719db8..5243f15a 100644 --- a/apps/mail/crates/mail-hooks/README.md +++ b/apps/mail/crates/mail-hooks/README.md @@ -57,6 +57,7 @@ export HOOKS_BIND_ADDR=127.0.0.1:8793 DEV_TRUST_UNVERIFIED_DOMAINS=on cargo run -p mail-hooks ``` -Embed: `mail_hooks::migrate(&pool).await?; app.merge(mail_hooks::router(HookState::new(pool, CoreHookSender::shared(store, cfg), HooksConfig::from_env())))`. +Embed (what mail-server does): `mail_hooks::migrate(&pool).await?; app.merge(mail_hooks::router(HookState::new(store, core_cfg, HooksConfig::from_env())))`. +Admin keys are resolved with `mail_core::authenticate_api_key`; sends go through `mail_core::CoreSender::for_account` (the same queue as `POST /emails`). Tables are `hook_projects` and `hook_deliveries` (idempotent SQL in `migrations/`, applied by `migrate`, independent of `_sqlx_migrations`). diff --git a/apps/mail/crates/mail-hooks/src/core_adapter.rs b/apps/mail/crates/mail-hooks/src/core_adapter.rs index b670ae54..dfb04df8 100644 --- a/apps/mail/crates/mail-hooks/src/core_adapter.rs +++ b/apps/mail/crates/mail-hooks/src/core_adapter.rs @@ -1,13 +1,11 @@ -//! The one place this crate touches `mail-core`: admin API-key checks and -//! the per-account sender that hands messages to the queue. If mail-core -//! grows a public `authenticate_api_key(pool, raw)`, only this file changes. +//! The one place this crate touches `mail-core`: the admin API-key check +//! (shared `mail_core::authenticate_api_key`) and the per-account send +//! through `mail_core::CoreSender` (the same queue as `POST /emails`). use std::sync::Arc; -use async_trait::async_trait; use axum::http::HeaderMap; -use mail_core::apikey::{hash_token, KEY_PREFIX}; -use mail_core::{CoreConfig, CoreSender, PgStore}; +use mail_core::{authenticate_api_key, CoreConfig, CoreSender, PgStore}; use mail_types::{EmailSender, OutgoingEmail, SendError}; use uuid::Uuid; @@ -21,7 +19,7 @@ pub struct AdminKey { pub name: String, } -/// `Authorization: Bearer sk_...` with `full_access`, checked the same way +/// `Authorization: Bearer sk_...` with `full_access`, resolved exactly like /// the HTTP API does. pub async fn authenticate_admin(store: &PgStore, headers: &HeaderMap) -> Result { let header = headers @@ -32,10 +30,9 @@ pub async fn authenticate_admin(store: &PgStore, headers: &HeaderMap) -> Result< .strip_prefix("Bearer ") .or_else(|| header.strip_prefix("bearer ")) .map(str::trim) - .filter(|t| !t.is_empty() && t.starts_with(KEY_PREFIX)) + .filter(|t| !t.is_empty()) .ok_or_else(|| HookError::Unauthorized("API key is invalid".into()))?; - let key = store - .api_key_by_hash(&hash_token(token)) + let key = authenticate_api_key(store, token) .await? .ok_or_else(|| HookError::Unauthorized("API key is invalid".into()))?; if !key.is_full_access() { @@ -45,36 +42,21 @@ pub async fn authenticate_admin(store: &PgStore, headers: &HeaderMap) -> Result< } Ok(AdminKey { account_id: key.account_id, - api_key_id: key.id, + api_key_id: key.api_key_id, name: key.name, }) } -/// Sends a hook email on behalf of the project's account. -#[async_trait] -pub trait HookSender: Send + Sync { - async fn send(&self, account_id: Uuid, email: OutgoingEmail) -> std::result::Result; -} - -/// The default: mail-core's own queue, `CoreSender::for_account`. -pub struct CoreHookSender { - store: PgStore, - cfg: Arc, -} - -impl CoreHookSender { - pub fn shared(store: PgStore, cfg: Arc) -> Arc { - Arc::new(Self { store, cfg }) - } -} - -#[async_trait] -impl HookSender for CoreHookSender { - async fn send(&self, account_id: Uuid, email: OutgoingEmail) -> std::result::Result { - CoreSender::for_account(self.store.clone(), self.cfg.clone(), account_id) - .send(email) - .await - } +/// Enqueue a hook email on behalf of the project's account. +pub async fn send_for_account( + store: &PgStore, + cfg: &Arc, + account_id: Uuid, + email: OutgoingEmail, +) -> std::result::Result { + CoreSender::for_account(store.clone(), cfg.clone(), account_id) + .send(email) + .await } /// Validate a `from` mailbox with mail-core's parser. diff --git a/apps/mail/crates/mail-hooks/src/lib.rs b/apps/mail/crates/mail-hooks/src/lib.rs index 1b5c6846..5a1e4eed 100644 --- a/apps/mail/crates/mail-hooks/src/lib.rs +++ b/apps/mail/crates/mail-hooks/src/lib.rs @@ -25,11 +25,10 @@ use std::sync::Arc; use axum::extract::DefaultBodyLimit; use axum::Router; -use mail_core::PgStore; +use mail_core::{CoreConfig, PgStore}; use sqlx::PgPool; pub use config::HooksConfig; -pub use core_adapter::{CoreHookSender, HookSender}; pub use error::HookError; /// Shared state; cheap to clone. @@ -37,16 +36,17 @@ pub use error::HookError; pub struct HookState { pub pool: PgPool, pub store: PgStore, - pub sender: Arc, + /// mail-core settings the per-account sends run with. + pub core_cfg: Arc, pub cfg: Arc, } impl HookState { - pub fn new(pool: PgPool, sender: Arc, cfg: HooksConfig) -> Self { + pub fn new(store: PgStore, core_cfg: Arc, cfg: HooksConfig) -> Self { Self { - store: PgStore::new(pool.clone()), - pool, - sender, + pool: store.pool().clone(), + store, + core_cfg, cfg: Arc::new(cfg), } } diff --git a/apps/mail/crates/mail-hooks/src/main.rs b/apps/mail/crates/mail-hooks/src/main.rs index 35af2a5b..cc659b92 100644 --- a/apps/mail/crates/mail-hooks/src/main.rs +++ b/apps/mail/crates/mail-hooks/src/main.rs @@ -9,7 +9,7 @@ use std::sync::Arc; use anyhow::Context; use mail_core::{CoreConfig, PgStore}; -use mail_hooks::{core_adapter, HookState, HooksConfig}; +use mail_hooks::{HookState, HooksConfig}; use sqlx::postgres::PgPoolOptions; use tower_http::trace::TraceLayer; @@ -79,8 +79,7 @@ async fn main() -> anyhow::Result<()> { .map_err(|e| anyhow::anyhow!("hook migrations: {e}"))?; let core_cfg = Arc::new(core_config()); - let sender = core_adapter::CoreHookSender::shared(store, core_cfg.clone()); - let state = HookState::new(pool, sender, HooksConfig::from_env()); + let state = HookState::new(store, core_cfg.clone(), HooksConfig::from_env()); let app = mail_hooks::router(state).layer(TraceLayer::new_for_http()); let bind = env_or("HOOKS_BIND_ADDR", "127.0.0.1:8793"); diff --git a/apps/mail/crates/mail-hooks/src/routes/hook.rs b/apps/mail/crates/mail-hooks/src/routes/hook.rs index b6964f10..364196a8 100644 --- a/apps/mail/crates/mail-hooks/src/routes/hook.rs +++ b/apps/mail/crates/mail-hooks/src/routes/hook.rs @@ -8,6 +8,7 @@ use mail_types::SendError; use serde_json::{json, Value}; use time::OffsetDateTime; +use crate::core_adapter::send_for_account; use crate::error::{HookError, Result}; use crate::payload::HookPayload; use crate::projects::{self, DeliveryRecord}; @@ -58,7 +59,7 @@ pub async fn receive( let mut email_ids = Vec::with_capacity(planned.len()); for p in planned { - match state.sender.send(project.account_id, p.email).await { + match send_for_account(&state.store, &state.core_cfg, project.account_id, p.email).await { Ok(id) => email_ids.push(id), Err(e) => { let err = send_error(e); diff --git a/apps/mail/crates/mail-inbound/README.md b/apps/mail/crates/mail-inbound/README.md index 7df638d0..acd72d3c 100644 --- a/apps/mail/crates/mail-inbound/README.md +++ b/apps/mail/crates/mail-inbound/README.md @@ -39,7 +39,11 @@ server source. Licence: MIT (workspace). - 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-core` wires it to `record_inbound_event`. + 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). diff --git a/apps/mail/crates/mail-mta/README.md b/apps/mail/crates/mail-mta/README.md index 2558fb81..300e8b40 100644 --- a/apps/mail/crates/mail-mta/README.md +++ b/apps/mail/crates/mail-mta/README.md @@ -114,12 +114,13 @@ approved` → secondary takes it, or with primary only → same for a header-From rejection at end-of-data; wrong AUTH password → probe fails, traffic goes to secondary. -**mail-core hook needed** (not editable from this crate): in `Worker`, when -`mail_mta::is_relay_rejection(&result)` is true, set the email status to -`failed` with the result message (no retry, no recipient suppression), and -wire `MAIL_TRANSPORT=relay-pool` → `Arc::new(RelayPool::from_env()?)` in -`mail-server/main.rs`, spawning `pool.spawn_health_checks()` and exposing -`pool.health()` on the status page. +**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) diff --git a/apps/mail/crates/mail-mta/src/relay/classify.rs b/apps/mail/crates/mail-mta/src/relay/classify.rs index 933ffe91..e009dbdd 100644 --- a/apps/mail/crates/mail-mta/src/relay/classify.rs +++ b/apps/mail/crates/mail-mta/src/relay/classify.rs @@ -8,8 +8,9 @@ use crate::reply::Reply; /// Prefix on every result message that describes a relay-side rejection of /// the whole message (sender/content), so `mail-core` can tell it apart from -/// a recipient bounce and must NOT suppress the recipient. -pub const RELAY_REJECTED_PREFIX: &str = "[relay-rejected]"; +/// a recipient bounce and must NOT suppress the recipient. Defined in +/// `mail-types` so the pipeline needs no dependency on this crate. +pub use mail_types::RELAY_REJECTED_PREFIX; /// Why a relay refused the whole transaction. #[derive(Debug, Clone, Copy, PartialEq, Eq)] @@ -118,5 +119,5 @@ pub fn unavailable_results(rcpts: &[String], detail: &str) -> Vec bool { - result.message.starts_with(RELAY_REJECTED_PREFIX) + result.is_relay_rejection() } diff --git a/apps/mail/crates/mail-oci/README.md b/apps/mail/crates/mail-oci/README.md index fb26774c..33195315 100644 --- a/apps/mail/crates/mail-oci/README.md +++ b/apps/mail/crates/mail-oci/README.md @@ -22,7 +22,7 @@ which DNS records to publish. This crate does exactly that. | Function | OCI resource | Notes | |---|---|---| | `ensure_email_domain(domain)` | `POST/GET /20170907/emailDomains` | Idempotent (find-by-name first, `opc-retry-token` on create). | -| `create_dkim(email_domain_id, selector)` | `POST/GET /dkims` | Returns `dns_subdomain_name` → `cname_record_value`, the CNAME the customer adds. Re-uses an existing key with the same selector. | +| `create_dkim(email_domain_id, selector)` | `POST/GET /dkims` | Returns `dns_subdomain_name` → `cname_record_value`, the CNAME the customer adds. Re-uses an existing key with the same selector. `onboard_domain` first reuses the domain's `active_dkim_id` (if any) so an already-signing domain never gets a second selector. | | `ensure_approved_sender(address)` | `POST/GET /senders` | One exact address per Sender. **There is no domain-wide / wildcard sender in the OCI API** (`CreateSenderDetails { compartmentId, emailAddress }`), so we approve each From address a customer uses. Tenancy limit: `approved-sender-count` (10 000 in ours). | | `ensure_email_return_path(email_domain_id, "bounce.")` | `POST/GET /emailReturnPaths` | Optional custom return path (CNAME) so the envelope sender aligns with the customer domain for SPF/DMARC. | | `list_suppressions` / `sync_suppressions(client, mirror, since)` | `GET /suppressions` (tenancy-scoped) | OCI keeps its own hard-bounce/complaint/unsubscribe list because the relay rewrites the envelope sender to its own return path and sees the bounces. We mirror it into ours through the `SuppressionMirror` trait (mail-core implements it on its suppression table; `MemoryMirror` is for dry runs). `create_suppression` pushes our unsubscribes back. | @@ -78,6 +78,14 @@ When a customer adds `example.com` and clicks verify: 4. Each new From address the customer uses goes through `ensure_approved_sender`; a send with an unapproved address is surfaced by `mail-mta`'s `RelayPool` as a `[relay-rejected]` result (never a recipient bounce). 5. `sync_suppressions` runs on a schedule with `since = last run` and pushes OCI's hard bounces / complaints into our suppression table. +Wired in `mail-server` (2026-11-13): `src/oci.rs` holds the client +(`OCI_ONBOARDING=on`), calls `onboard_domain` from `POST /domains` and +`POST /domains/{id}/verify`, maps `CustomerDnsRecords` onto the Resend-shaped +`records[]`, implements `SuppressionMirror` on `mail_global_suppressions` +(`GlobalSuppressionMirror`) and runs the sync every +`OCI_SUPPRESSION_SYNC_SECS` (default 900) with the last run kept in +`mail_settings.oci_suppression_sync_since`. + Verification status for the customer = our DNS checks (SPF/DKIM/DMARC) **and** OCI's `Dkim.lifecycle_state == ACTIVE` and every `Sender.lifecycle_state == ACTIVE`. diff --git a/apps/mail/crates/mail-oci/src/onboarding.rs b/apps/mail/crates/mail-oci/src/onboarding.rs index 2be8cdd7..4792de1a 100644 --- a/apps/mail/crates/mail-oci/src/onboarding.rs +++ b/apps/mail/crates/mail-oci/src/onboarding.rs @@ -42,7 +42,14 @@ pub async fn onboard_domain( dmarc_rua: &str, ) -> Result { let email_domain = client.ensure_email_domain(domain).await?; - let dkim = client.create_dkim(&email_domain.id, dkim_selector).await?; + // A domain that already signs with an active OCI key keeps it: creating a + // second selector would make OCI switch keys before the customer has + // published the new CNAME (the scribase.com case, selector + // `scribase-fra-20260926`). + let dkim = match &email_domain.active_dkim_id { + Some(active) => client.get_dkim(active).await?, + None => client.create_dkim(&email_domain.id, dkim_selector).await?, + }; let return_path = match return_path_subdomain { Some(sub) => Some( client diff --git a/apps/mail/crates/mail-server/Cargo.toml b/apps/mail/crates/mail-server/Cargo.toml index 85288219..0af16620 100644 --- a/apps/mail/crates/mail-server/Cargo.toml +++ b/apps/mail/crates/mail-server/Cargo.toml @@ -16,7 +16,14 @@ path = "src/main.rs" [dependencies] mail-core = { path = "../mail-core" } mail-auth = { path = "../mail-auth" } +# Mounted routers and embedded services (one binary, one Postgres). +mail-hooks = { path = "../mail-hooks" } +mail-submit = { path = "../mail-submit" } +mail-inbound = { path = "../mail-inbound" } +mail-mta = { path = "../mail-mta" } +mail-oci = { path = "../mail-oci" } mail-types.workspace = true +async-trait.workspace = true serde.workspace = true serde_json.workspace = true thiserror.workspace = true @@ -30,6 +37,8 @@ tracing = "0.1" tracing-subscriber = { version = "0.3", features = ["env-filter"] } uuid = { version = "1", features = ["v4", "serde"] } time = { version = "0.3", features = ["serde", "formatting", "parsing", "macros"] } +# `since` timestamps for the OCI suppression mirror (mail-oci speaks chrono). +chrono = { version = "0.4", default-features = false, features = ["clock", "std"] } sha2 = "0.10" # Dashboard session JWTs (EdDSA / Ed25519, RFC 8037) verified against mail-auth's JWKS. diff --git a/apps/mail/crates/mail-server/README.md b/apps/mail/crates/mail-server/README.md index 1b92e9dd..1a591a39 100644 --- a/apps/mail/crates/mail-server/README.md +++ b/apps/mail/crates/mail-server/README.md @@ -54,27 +54,54 @@ Extra names: `forbidden` (403), `missing_account_id` (400), `account_paused` / ```sh createdb mail_dev -export DATABASE_URL=postgres://localhost/mail_dev +export DATABASE_URL=postgres://$USER@localhost/mail_dev # include the user: the inbound store (sqlx 0.9) does not default it export PUBLIC_BASE_URL=https://mail.scribase.com # links in mail: unsubscribe, tracking, invites, magic links -export SMTP_HOST=smtp.email.eu-frankfurt-1.oci.oraclecloud.com SMTP_PORT=587 SMTP_USER=... SMTP_PASS=... +export SMTP_USER=... SMTP_PASS=... # OCI Email Delivery SMTP credentials (relay pool primary, OCI_REGION=eu-frankfurt-1) +export PUBLIC_BOUNCE_DOMAIN=bounce.scribase.com # VERP return path, routed by Cloudflare Email Routing to the ingest below export AUTH_SIGNING_KEY=... # 32-byte Ed25519 seed (mail-auth); AUTH_ADMIN_TOKEN=... for /auth/admin export DASHBOARD_JWT_AUDIENCE=scribase-mail # = the mail-auth project's jwt_audience export SYSTEM_FROM_ADDRESS="Scribase Mail " # invitation emails, domain of the system account +export SUBMIT_TLS_CERT=/etc/mail/fullchain.pem SUBMIT_TLS_KEY=/etc/mail/privkey.pem # enables SMTP submission on 587/465 +export INBOUND_HTTP_SECRET=... INBOUND_HTTP_LISTEN=127.0.0.1:8585 INBOUND_DOMAINS=bounce.scribase.com # enables POST /inbound/raw +export OCI_ONBOARDING=on # create domains on OCI + mirror its suppressions (OCI_* or ~/.oci/config) cargo run -p mail-server -- create-key --name bootstrap # system-account key, printed once cargo run -p mail-server # listens on BIND_ADDR (127.0.0.1:8790) ``` Bootstrap order: `create-key` → `POST /domains` for your own domain with that -key → `POST /auth/admin/projects` (from-address on that domain) → users sign -in with magic links and `POST /accounts`. +key → `POST /auth/admin/projects` (bare from-address on that domain) → users +sign in with magic links and `POST /accounts`. -Dev-only flags: `SMTP_TLS=off` (plaintext to a local sink), -`DEV_TRUST_UNVERIFIED_DOMAINS=on`, `WEBHOOK_ALLOW_PRIVATE=on`. Full env table -in `src/main.rs`. +Dev-only flags: `DEV_TRUST_UNVERIFIED_DOMAINS=on`, `WEBHOOK_ALLOW_PRIVATE=on`, +`RELAY_PRIMARY_HOST=127.0.0.1 RELAY_PRIMARY_TLS=none` (a local SMTP sink as the +relay), `SMTP_TLS=off` (legacy `MAIL_TRANSPORT=relay`). Full env table in +`src/main.rs`. + +## What runs inside the process + +| Piece | Module | Enabled by | +|---|---|---| +| Resend-compatible API + accounts | `routes/*` | always | +| mail-auth login router (`/auth/*`, JWKS) | `main.rs` | always | +| mail-hooks Supabase Send Email Hook (`/hooks/*`) | `main.rs` | always | +| Outbound `RelayPool` (OCI primary, failover, quotas); `/healthz` shows relay health | `transport.rs` | `MAIL_TRANSPORT=relay-pool` (default) | +| SMTP submission 587/465 (`mail_core::authenticate_api_key` + `enqueue_raw`) | `submit.rs` | `SUBMIT_TLS_CERT` | +| Inbound HTTPS ingest; DSN/ARF → `mail_core::record_inbound_event` (status, suppression, webhooks) | `inbound.rs` | `INBOUND_HTTP_SECRET` | +| OCI onboarding on domain create/verify + suppression mirror (`OCI_SUPPRESSION_SYNC_SECS`) | `oci.rs` | `OCI_ONBOARDING=on` | + +Relay rejections (`[relay-rejected] …`, e.g. an OCI "sender not approved") mark +the email `failed` with the relay's text and never suppress the recipient. + +With OCI onboarding on, `POST /domains` (optionally `"senders": [...]`) and +`POST /domains/{id}/verify` create the OCI email domain, reuse or create its +DKIM key, approve the From addresses (verify approves every address the +account has used on the domain) and return `records[]` with the OCI DKIM +CNAME, our DKIM TXT, SPF (`@`) and DMARC; the response also carries `relay` +(`dkim_state`, `senders`, `sender_failures`). A domain becomes `verified` +only when the DNS checks pass and OCI reports the DKIM key `ACTIVE`. ## Mounting other routers `mail_server::build_app(state, extra: axum::Router) -> axum::Router` merges -`extra` into the app; `main.rs` mounts `mail_auth::router(...)` this way with -the shared pool and `CoreSender`. `MAIL_TRANSPORT=relay|direct` selects the -outbound transport; `direct` is the slot for `mail-mta`. +`extra` into the app; `main.rs` mounts `mail_auth::router(...)` and +`mail_hooks::router(...)` this way with the shared pool. diff --git a/apps/mail/crates/mail-server/src/env.rs b/apps/mail/crates/mail-server/src/env.rs new file mode 100644 index 00000000..9c607474 --- /dev/null +++ b/apps/mail/crates/mail-server/src/env.rs @@ -0,0 +1,38 @@ +//! Environment helpers shared by the binary and the service modules. + +use anyhow::Context; + +pub fn required(name: &str) -> anyhow::Result { + std::env::var(name).with_context(|| format!("{name} must be set")) +} + +pub fn opt(name: &str) -> Option { + std::env::var(name) + .ok() + .map(|v| v.trim().to_owned()) + .filter(|v| !v.is_empty()) +} + +pub fn or(name: &str, default: &str) -> String { + opt(name).unwrap_or_else(|| default.to_string()) +} + +pub fn flag(name: &str) -> bool { + matches!( + opt(name).map(|v| v.to_ascii_lowercase()).as_deref(), + Some("on" | "true" | "1" | "yes") + ) +} + +/// Parse a numeric variable, falling back to `default` when unset. +pub fn parse(name: &str, default: T) -> anyhow::Result +where + T::Err: std::fmt::Display, +{ + match opt(name) { + None => Ok(default), + Some(v) => v + .parse::() + .map_err(|e| anyhow::anyhow!("{name}={v}: {e}")), + } +} diff --git a/apps/mail/crates/mail-server/src/inbound.rs b/apps/mail/crates/mail-server/src/inbound.rs new file mode 100644 index 00000000..7909e017 --- /dev/null +++ b/apps/mail/crates/mail-server/src/inbound.rs @@ -0,0 +1,133 @@ +//! Inbound feedback: `mail-inbound`'s HTTPS ingest (`POST /inbound/raw`, fed +//! by the Cloudflare Email Worker) runs inside this process, and its sink +//! turns DSNs and ARF complaints into `mail_core::record_inbound_event` +//! calls, so bounces and complaints update the email, the suppression lists +//! and fire the account's webhooks. + +use std::net::SocketAddr; +use std::sync::Arc; + +use async_trait::async_trait; +use mail_core::{record_inbound_event, InboundDetail, InboundEventKind}; +use mail_inbound::{ + BounceDetail, ComplaintDetail, HttpIngest, InboundConfig, InboundSink, IngestConfig, + ReceivedMessage, +}; +use sqlx::PgPool; +use uuid::Uuid; + +/// `InboundSink` over mail-core's event log. +pub struct CoreInboundSink { + pool: PgPool, +} + +impl CoreInboundSink { + pub fn new(pool: PgPool) -> Self { + Self { pool } + } +} + +/// VERP ids are the email UUID (`bounces+@…`). +fn email_id(id: &str) -> Option { + Uuid::parse_str(id.trim()).ok() +} + +fn non_empty(s: String) -> Option { + (!s.trim().is_empty()).then_some(s) +} + +/// SMTP reply class from an RFC 3463 status (`5.1.1` → 550, `4.x.x` → 450). +fn code_from_status(status: &str) -> Option { + match status.trim().chars().next() { + Some('5') => Some(550), + Some('4') => Some(450), + _ => None, + } +} + +async fn apply(pool: &PgPool, id: &str, kind: InboundEventKind, detail: InboundDetail) { + let Some(email_id) = email_id(id) else { + tracing::warn!(id, ?kind, "inbound report for a non-UUID mail id; ignored"); + return; + }; + match record_inbound_event(pool, email_id, kind, detail).await { + Ok(()) => tracing::info!(email = %email_id, ?kind, "inbound report applied"), + Err(e) => tracing::warn!(email = %email_id, ?kind, error = %e, "inbound report not applied"), + } +} + +#[async_trait] +impl InboundSink for CoreInboundSink { + async fn bounce(&self, id: &str, hard: bool, detail: BounceDetail) { + let kind = if hard { + InboundEventKind::Bounce + } else { + InboundEventKind::Delayed + }; + let message = detail + .diagnostic + .clone() + .filter(|d| !d.trim().is_empty()) + .unwrap_or_else(|| format!("{} {}", detail.action, detail.status).trim().to_owned()); + apply( + &self.pool, + id, + kind, + InboundDetail { + recipient: non_empty(detail.recipient), + code: code_from_status(&detail.status), + message, + }, + ) + .await; + } + + async fn complaint(&self, id: &str, detail: ComplaintDetail) { + let message = format!( + "{} complaint reported by {}", + if detail.feedback_type.is_empty() { "abuse" } else { &detail.feedback_type }, + detail.reporter + ); + apply( + &self.pool, + id, + InboundEventKind::Complaint, + InboundDetail { + recipient: detail.original_rcpt_to.and_then(non_empty), + code: None, + message, + }, + ) + .await; + } + + async fn received(&self, msg: ReceivedMessage) { + // Ordinary inbound mail is stored by mail-inbound; there is no + // inbox product on top of it yet, so just leave a trace. + tracing::info!(id = %msg.id, domain = %msg.domain, from = %msg.mail_from, to = ?msg.rcpt_to, subject = ?msg.subject, stored_at = ?msg.stored_at, "inbound message received"); + } +} + +/// Start the HTTPS ingest when `INBOUND_HTTP_SECRET` / `INBOUND_HTTP_LISTEN` +/// are set (needs `INBOUND_DOMAINS`). Returns the bound address. +pub async fn spawn_http_ingest(pool: PgPool) -> anyhow::Result> { + if !IngestConfig::enabled_by_env() { + tracing::info!("inbound HTTPS ingest disabled (INBOUND_HTTP_SECRET unset)"); + return Ok(None); + } + let inbound = InboundConfig::from_env().map_err(|e| anyhow::anyhow!("inbound config: {e}"))?; + let ingest = IngestConfig::from_env().map_err(|e| anyhow::anyhow!("ingest config: {e}"))?; + let sink: Arc = Arc::new(CoreInboundSink::new(pool)); + let server = HttpIngest::bind_standalone(inbound, ingest, sink) + .await + .map_err(|e| anyhow::anyhow!("binding inbound ingest: {e}"))?; + let addr = server + .local_addr() + .map_err(|e| anyhow::anyhow!("inbound ingest address: {e}"))?; + tokio::spawn(async move { + if let Err(e) = server.run().await { + tracing::error!(error = %e, "inbound HTTPS ingest stopped"); + } + }); + Ok(Some(addr)) +} diff --git a/apps/mail/crates/mail-server/src/lib.rs b/apps/mail/crates/mail-server/src/lib.rs index 26d8e8f0..93bb0ff8 100644 --- a/apps/mail/crates/mail-server/src/lib.rs +++ b/apps/mail/crates/mail-server/src/lib.rs @@ -4,9 +4,12 @@ //! JSON API (`/emails`, `/domains`, `/api-keys`, `/webhooks`, //! `/suppressions`), account management (`/accounts`, members, invitations, //! `/usage`, `/audit-log`), the hosted unsubscribe and tracking endpoints, -//! `/healthz`, the mounted `mail-auth` login router, and the background send -//! and webhook workers. Independent implementation, written without -//! reference to useSend source. +//! `/healthz`, the mounted `mail-auth` login router and `mail-hooks` Supabase +//! hook router, the embedded SMTP submission listeners (`mail-submit`), the +//! inbound HTTPS ingest (`mail-inbound`), the OCI control plane (`mail-oci`: +//! domain onboarding + suppression mirror), the `RelayPool` transport +//! (`mail-mta`) and the background send and webhook workers. Independent +//! implementation, written without reference to useSend source. //! //! Credentials: `Authorization: Bearer sk_...` (API key, live or `sk_test_`) //! or `Bearer ` + `X-Account-Id`. @@ -27,10 +30,15 @@ //! | `GET /healthz`, `GET|POST /unsubscribe/{token}`, `GET /track/...` | public | none | pub mod auth; +pub mod env; pub mod error; +pub mod inbound; pub mod jwt; +pub mod oci; pub mod routes; pub mod state; +pub mod submit; +pub mod transport; pub mod views; use axum::extract::DefaultBodyLimit; diff --git a/apps/mail/crates/mail-server/src/main.rs b/apps/mail/crates/mail-server/src/main.rs index 80b7dc04..29d255ea 100644 --- a/apps/mail/crates/mail-server/src/main.rs +++ b/apps/mail/crates/mail-server/src/main.rs @@ -1,17 +1,22 @@ -//! Binary entry point: sending API + workers + the mounted mail-auth router, -//! one Postgres pool, both migration sets. +//! Binary entry point: the sending API, the mounted mail-auth and mail-hooks +//! routers, the SMTP submission listeners, the inbound HTTPS ingest, the OCI +//! control plane and the send + webhook workers. One process, one Postgres. //! //! | Var | Meaning | Default | //! |-----|---------|---------| //! | `DATABASE_URL` | Postgres connection string | *required* | //! | `PUBLIC_BASE_URL` | external base URL for unsubscribe/tracking/invite links | *required* | //! | `BIND_ADDR` | listen address | `127.0.0.1:8790` | -//! | `SMTP_HOST` / `SMTP_PORT` / `SMTP_USER` / `SMTP_PASS` | relay smarthost (STARTTLS) | host required when `MAIL_TRANSPORT=relay`; port `587` | -//! | `SMTP_TLS` | `off` disables STARTTLS (dev sink only) | `on` | -//! | `MAIL_TRANSPORT` | `relay` (lettre smarthost) or `direct` (mail-mta, mounted by the integrator) | `relay` | +//! | `MAIL_TRANSPORT` | `relay-pool` (mail-mta `RelayPool`, `RELAY_*`), `relay` (lettre, `SMTP_*`) or `direct` (parked, no port 25) | `relay-pool` | +//! | `RELAY_PRIMARY_*` … | relay pool slots; primary defaults to OCI in `OCI_REGION`, credentials fall back to `SMTP_USER/PASS` (see `mail-mta` README) | | +//! | `SMTP_HOST` / `SMTP_PORT` / `SMTP_USER` / `SMTP_PASS` / `SMTP_TLS` | legacy smarthost for `MAIL_TRANSPORT=relay`; also the relay pool's fallback | | +//! | `OCI_ONBOARDING` | `on`: create/verify domains on OCI Email Delivery and mirror its suppressions (`OCI_*`, see `src/oci.rs`) | off | +//! | `SUBMIT_TLS_CERT` / `SUBMIT_TLS_KEY` / `SUBMIT_*` | set the cert to enable SMTP submission on 587/465 (see `mail-submit`) | off | +//! | `INBOUND_HTTP_SECRET` / `INBOUND_HTTP_LISTEN` / `INBOUND_DOMAINS` / `INBOUND_*` | set the secret to enable the inbound HTTPS ingest (see `mail-inbound`) | off | +//! | `HOOKS_*` | Supabase Send Email Hook settings (see `mail-hooks`) | | //! | `PUBLIC_BOUNCE_DOMAIN` | VERP return-path domain | `.` | //! | `DKIM_SELECTOR` | DKIM selector | `scribase` | -//! | `SPF_VALUE` | SPF TXT customers publish on the return-path subdomain | `v=spf1 include:rp.oracleemaildelivery.com ~all` | +//! | `SPF_VALUE` | SPF TXT customers publish on the return-path subdomain (no-OCI mode) | `v=spf1 include:rp.oracleemaildelivery.com ~all` | //! | `RETURN_PATH_MX` | MX host for the return-path subdomain (our inbound) | *(no MX record)* | //! | `RATE_LIMIT_PER_SECOND` | per-caller request budget | `10` | //! | `DEV_TRUST_UNVERIFIED_DOMAINS` | `on` sends from unverified domains (dev) | `off` | @@ -32,33 +37,16 @@ use std::time::Duration; use anyhow::{bail, Context}; use mail_auth::{AuthConfig, AuthState, SigningKeys}; use mail_core::store::NewApiKeyRow; -use mail_core::{apikey, CoreConfig, CoreSender, PgStore, RelayTransport, SmtpConfig, Worker}; -use mail_server::build_app; +use mail_core::{apikey, CoreConfig, CoreSender, PgStore, Worker}; +use mail_hooks::{HookState, HooksConfig}; +use mail_server::env::{flag as env_flag, opt as env_opt, or as env_or, required as env_required}; use mail_server::jwt::JwtVerifier; use mail_server::state::{AppState, RateLimiter}; -use mail_types::{EmailSender, Transport}; +use mail_server::{build_app, inbound, oci, submit, transport}; +use mail_types::EmailSender; use sqlx::postgres::PgPoolOptions; -fn env_required(name: &str) -> anyhow::Result { - std::env::var(name).with_context(|| format!("{name} must be set")) -} - -fn env_opt(name: &str) -> Option { - std::env::var(name).ok().filter(|v| !v.is_empty()) -} - -fn env_or(name: &str, default: &str) -> String { - env_opt(name).unwrap_or_else(|| default.to_string()) -} - -fn env_flag(name: &str) -> bool { - matches!( - env_opt(name).map(|v| v.to_ascii_lowercase()).as_deref(), - Some("on" | "true" | "1" | "yes") - ) -} - -fn core_config(transport: &str) -> anyhow::Result { +fn core_config(final_hop: bool) -> anyhow::Result { let public_base_url = env_required("PUBLIC_BASE_URL")? .trim_end_matches('/') .to_string(); @@ -76,51 +64,10 @@ fn core_config(transport: &str) -> anyhow::Result { return_path_mx: env_opt("RETURN_PATH_MX"), trust_unverified_domains: env_flag("DEV_TRUST_UNVERIFIED_DOMAINS"), allow_private_webhooks: env_flag("WEBHOOK_ALLOW_PRIVATE"), - transport_is_final_hop: transport == "direct", + transport_is_final_hop: final_hop, }) } -fn smtp_config() -> anyhow::Result { - let host = env_required("SMTP_HOST")?; - let port = env_or("SMTP_PORT", "587") - .parse::() - .context("SMTP_PORT must be a port number")?; - let tls = !matches!( - std::env::var("SMTP_TLS").ok().as_deref(), - Some("off" | "false" | "0") - ); - let username = env_opt("SMTP_USER"); - let password = env_opt("SMTP_PASS"); - if tls && (username.is_none() || password.is_none()) { - bail!("SMTP_USER and SMTP_PASS must be set for the relay (or SMTP_TLS=off for a local dev sink)"); - } - Ok(SmtpConfig { - host, - port, - username, - password, - tls, - }) -} - -/// Pick the outbound transport. `direct` is the slot for `mail-mta`, which the -/// integrating session wires in; until then it is a clear startup error. -fn build_transport(kind: &str) -> anyhow::Result> { - match kind { - "relay" => { - let cfg = smtp_config()?; - tracing::info!(host = %cfg.host, port = cfg.port, tls = cfg.tls, "transport = relay (lettre STARTTLS smarthost)"); - Ok(Arc::new( - RelayTransport::new(&cfg).map_err(|e| anyhow::anyhow!(e.to_string()))?, - )) - } - "direct" => { - bail!("MAIL_TRANSPORT=direct requires the mail-mta transport to be mounted in main.rs") - } - other => bail!("MAIL_TRANSPORT must be `relay` or `direct`, got `{other}`"), - } -} - /// `create-key --name X [--permission P] [--domain-id D] [--account-id A] [--test]` async fn create_key(store: &PgStore, args: &[String]) -> anyhow::Result<()> { let arg = |flag: &str| { @@ -175,7 +122,8 @@ fn init_tracing() { tracing_subscriber::fmt().with_env_filter(filter).init(); } -/// Connect to Postgres and run both migration sets (mail-core, mail-auth). +/// Connect to Postgres and run every migration set that shares the pool +/// (mail-core, mail-auth, mail-hooks). async fn connect_store() -> anyhow::Result { let database_url = env_required("DATABASE_URL")?; let pool = PgPoolOptions::new() @@ -191,6 +139,9 @@ async fn connect_store() -> anyhow::Result { mail_auth::migrate(&pool) .await .context("running mail-auth migrations")?; + mail_hooks::migrate(&pool) + .await + .map_err(|e| anyhow::anyhow!("running mail-hooks migrations: {e}"))?; Ok(store) } @@ -227,12 +178,13 @@ async fn jwt_verifier( Ok(Arc::new(verifier)) } -/// Build state from env, spawning the send and webhook workers, and the -/// mail-auth router sharing the same pool and `CoreSender`. +/// Build state from env; spawn the send/webhook workers, SMTP submission, +/// the inbound ingest and the OCI suppression mirror; build the extra +/// routers (mail-auth, mail-hooks) that share the pool. async fn build_state(store: PgStore) -> anyhow::Result<(AppState, axum::Router)> { - let transport_kind = env_or("MAIL_TRANSPORT", "relay"); - let cfg = Arc::new(core_config(&transport_kind)?); - let transport = build_transport(&transport_kind)?; + let transport_kind = env_or("MAIL_TRANSPORT", "relay-pool"); + let outbound = transport::build(&transport_kind)?; + let cfg = Arc::new(core_config(outbound.final_hop)?); let secret = mail_core::load_signing_secret(&store) .await .map_err(|e| anyhow::anyhow!(e.to_string()))?; @@ -243,9 +195,20 @@ async fn build_state(store: PgStore) -> anyhow::Result<(AppState, axum::Router)> .parse::() .context("INVITE_TTL_HOURS must be a number")?; - tokio::spawn(Worker::new(store.clone(), cfg.clone(), secret.clone(), transport).run()); + tokio::spawn(Worker::new(store.clone(), cfg.clone(), secret.clone(), outbound.transport).run()); tokio::spawn(mail_core::webhooks::run_delivery_worker(store.clone())); + if let Some(summary) = submit::spawn(store.clone(), cfg.clone())? { + tracing::info!(%summary, "SMTP submission enabled"); + } + if let Some(addr) = inbound::spawn_http_ingest(store.pool().clone()).await? { + tracing::info!(%addr, "inbound HTTPS ingest enabled (POST /inbound/raw)"); + } + let oci = oci::Oci::from_env(&cfg)?; + if let Some(oci) = &oci { + oci::spawn_suppression_sync(oci.clone(), store.clone()); + } + let auth_cfg = auth_config(&cfg)?; let keys = SigningKeys::from_env_or_generate(AuthConfig::is_production()) .context("mail-auth signing key")?; @@ -253,6 +216,11 @@ async fn build_state(store: PgStore) -> anyhow::Result<(AppState, axum::Router)> let sender: Arc = Arc::new(CoreSender::new(store.clone(), cfg.clone())); let auth_router = mail_auth::router(AuthState::new(store.pool().clone(), sender, keys, auth_cfg)); + let hooks_router = mail_hooks::router(HookState::new( + store.clone(), + cfg.clone(), + HooksConfig::from_env(), + )); let state = AppState { store, @@ -262,8 +230,10 @@ async fn build_state(store: PgStore) -> anyhow::Result<(AppState, axum::Router)> jwt: Some(jwt), system_from: env_opt("SYSTEM_FROM_ADDRESS"), invite_ttl: Duration::from_secs(invite_hours * 3600), + oci, + relay_pool: outbound.relay_pool, }; - Ok((state, auth_router)) + Ok((state, auth_router.merge(hooks_router))) } #[tokio::main] @@ -276,15 +246,15 @@ async fn main() -> anyhow::Result<()> { return create_key(&store, &args[1..]).await; } - let (state, auth_router) = build_state(store).await?; + let (state, extra) = build_state(store).await?; let cfg = state.cfg.clone(); - let app = build_app(state, auth_router); + let app = build_app(state, extra); let bind = env_or("BIND_ADDR", "127.0.0.1:8790"); let listener = tokio::net::TcpListener::bind(&bind) .await .with_context(|| format!("binding {bind}"))?; - tracing::info!(%bind, public_base_url = %cfg.public_base_url, dev_trust_unverified = cfg.trust_unverified_domains, "scribase mail listening (api + auth)"); + tracing::info!(%bind, public_base_url = %cfg.public_base_url, dev_trust_unverified = cfg.trust_unverified_domains, "scribase mail listening (api + auth + hooks)"); axum::serve( listener, app.into_make_service_with_connect_info::(), diff --git a/apps/mail/crates/mail-server/src/oci.rs b/apps/mail/crates/mail-server/src/oci.rs new file mode 100644 index 00000000..96173f00 --- /dev/null +++ b/apps/mail/crates/mail-server/src/oci.rs @@ -0,0 +1,179 @@ +//! OCI Email Delivery control plane, as used by the API process: onboard a +//! customer domain (OCI email domain + DKIM + approved senders) and turn the +//! result into the Resend-shaped `records[]` the customer publishes, plus the +//! suppression mirror that copies OCI's hard bounces / complaints onto our +//! global list on a schedule. +//! +//! | Var | Meaning | Default | +//! |---|---|---| +//! | `OCI_ONBOARDING` | `on` enables everything here (credentials: `OCI_*` or `~/.oci/config`) | off | +//! | `OCI_DKIM_SELECTOR` | selector for OCI-managed DKIM keys we create | `scribase-oci` | +//! | `OCI_CUSTOM_RETURN_PATH` | `on` also registers `.` as an OCI return path (one more CNAME) | off | +//! | `OCI_SUPPRESSION_SYNC_SECS` | mirror interval; `0` disables | `900` | +//! | `DMARC_RUA` | `rua=` address in the DMARC record we hand out | `dmarc@` | + +use std::sync::Arc; +use std::time::Duration; + +use async_trait::async_trait; +use chrono::{DateTime, Duration as ChronoDuration, Utc}; +use mail_core::model::{DnsRecord, Domain}; +use mail_core::{dns, CoreConfig, PgStore}; +use mail_oci::{ + onboard_domain, sync_suppressions, DomainOnboarding, OciClient, OciError, Suppression, + SuppressionMirror, +}; + +use crate::env; + +/// `mail_settings` key holding the last successful mirror run (RFC 3339). +pub const SYNC_SINCE_KEY: &str = "oci_suppression_sync_since"; +/// Re-fetch this much before the last run so a slow OCI write is not missed. +const SYNC_OVERLAP_MINUTES: i64 = 10; + +pub struct Oci { + pub client: OciClient, + pub dkim_selector: String, + pub custom_return_path: bool, + pub dmarc_rua: String, + pub sync_interval: Duration, +} + +impl Oci { + /// `None` unless `OCI_ONBOARDING=on`. Credentials are never read otherwise, + /// so a developer machine with `~/.oci/config` does not talk to the tenancy. + pub fn from_env(core: &CoreConfig) -> anyhow::Result>> { + if !env::flag("OCI_ONBOARDING") { + tracing::info!("OCI onboarding disabled (OCI_ONBOARDING unset); domains get our own records only"); + return Ok(None); + } + let client = OciClient::from_env().map_err(|e| anyhow::anyhow!("OCI config: {e}"))?; + let collector = core + .bounce_domain + .clone() + .unwrap_or_else(|| "scribase.com".into()); + let oci = Arc::new(Oci { + client, + dkim_selector: env::or("OCI_DKIM_SELECTOR", "scribase-oci"), + custom_return_path: env::flag("OCI_CUSTOM_RETURN_PATH"), + dmarc_rua: env::or("DMARC_RUA", &format!("dmarc@{collector}")), + sync_interval: Duration::from_secs(env::parse("OCI_SUPPRESSION_SYNC_SECS", 900u64)?), + }); + tracing::info!(region = %oci.client.config().region, selector = %oci.dkim_selector, rua = %oci.dmarc_rua, sync_secs = oci.sync_interval.as_secs(), "OCI onboarding enabled"); + Ok(Some(oci)) + } + + /// Make OCI ready to relay for `domain` (idempotent) and approve `senders`. + pub async fn onboard( + &self, + domain: &Domain, + senders: &[String], + ) -> Result { + let own_txt = format!("v=DKIM1; k=rsa; p={}", domain.dkim_public_key_b64); + onboard_domain( + &self.client, + &domain.name, + &self.dkim_selector, + senders, + self.custom_return_path + .then_some(domain.return_path.as_str()), + Some((&domain.dkim_selector, &own_txt)), + &self.dmarc_rua, + ) + .await + } + + /// OCI's customer records in our `records[]` shape (names relative to + /// the domain, `@` for the apex), all `not_started`. + pub fn records(domain: &Domain, onboarding: &DomainOnboarding) -> Vec { + onboarding + .dns + .records + .iter() + .map(|r| { + let name = dns::relative_name(&r.name, &domain.name); + let kind = if name.contains("_domainkey") { + "DKIM" + } else if name.starts_with("_dmarc") { + "DMARC" + } else { + "SPF" + }; + dns::record(kind, &name, &r.kind, r.value.clone(), None, Some(&r.purpose)) + }) + .collect() + } +} + +/// Writes OCI suppressions onto `mail_global_suppressions`: the relay sees +/// bounces and complaints for every tenant, so its list protects everyone. +pub struct GlobalSuppressionMirror { + pub store: PgStore, +} + +fn reason_for(entry: &Suppression) -> &'static str { + match entry + .reason + .as_deref() + .map(str::to_ascii_uppercase) + .as_deref() + { + Some("HARDBOUNCE") => "hard_bounce", + Some("COMPLAINT") => "complaint", + Some("UNSUBSCRIBE") => "unsubscribe", + Some("MANUAL") => "manual", + Some("SOFTBOUNCE") => "soft_bounce", + _ => "relay_suppression", + } +} + +#[async_trait] +impl SuppressionMirror for GlobalSuppressionMirror { + async fn upsert(&self, entry: &Suppression) -> Result { + let detail = format!( + "oci {} {}", + entry.id, + entry.error_detail.clone().unwrap_or_default() + ); + self.store + .upsert_global_suppression(&entry.email_address, reason_for(entry), Some(detail.trim())) + .await + .map_err(|e| e.to_string()) + } +} + +async fn last_sync(store: &PgStore) -> Option> { + let raw = store.setting(SYNC_SINCE_KEY).await.ok().flatten()?; + DateTime::parse_from_rfc3339(&raw) + .ok() + .map(|t| t.with_timezone(&Utc) - ChronoDuration::minutes(SYNC_OVERLAP_MINUTES)) +} + +/// Periodic mirror: first run at start-up, then every `sync_interval`. +/// `since` is the last successful run (minus an overlap) kept in `mail_settings`. +pub fn spawn_suppression_sync(oci: Arc, store: PgStore) -> Option> { + if oci.sync_interval.is_zero() { + tracing::info!("OCI suppression sync disabled (OCI_SUPPRESSION_SYNC_SECS=0)"); + return None; + } + Some(tokio::spawn(async move { + let mirror = GlobalSuppressionMirror { + store: store.clone(), + }; + let mut tick = tokio::time::interval(oci.sync_interval); + loop { + tick.tick().await; + let since = last_sync(&store).await; + let started = Utc::now(); + match sync_suppressions(&oci.client, &mirror, since).await { + Ok(report) => { + tracing::info!(fetched = report.fetched, inserted = report.inserted, failed = report.failed, since = ?since.map(|t| t.to_rfc3339()), "OCI suppression mirror run"); + if let Err(e) = store.set_setting(SYNC_SINCE_KEY, &started.to_rfc3339()).await { + tracing::warn!(error = %e, "could not record OCI sync time"); + } + } + Err(e) => tracing::warn!(error = %e, "OCI suppression mirror failed; will retry"), + } + } + })) +} diff --git a/apps/mail/crates/mail-server/src/routes/domains.rs b/apps/mail/crates/mail-server/src/routes/domains.rs index af8138ff..383b1331 100644 --- a/apps/mail/crates/mail-server/src/routes/domains.rs +++ b/apps/mail/crates/mail-server/src/routes/domains.rs @@ -1,20 +1,29 @@ //! `/domains`: register a sending domain (generates its DKIM key and the DNS //! records to publish), list/get/update/delete, and real DNS verification. //! A name can be held `verified` by one account only. +//! +//! With `OCI_ONBOARDING=on` the create and verify calls also onboard the +//! domain on OCI Email Delivery (email domain, DKIM, approved senders) and +//! `records[]` becomes OCI's list: the OCI DKIM CNAME, our DKIM TXT, SPF and +//! DMARC (plus the return-path CNAME when enabled). A domain is `verified` +//! only when our DNS checks pass and OCI reports its DKIM key ACTIVE. use axum::extract::{Path, State}; use axum::http::StatusCode; use axum::routing::{get, post}; use axum::{Json, Router}; -use mail_core::address::validate_domain; +use mail_core::address::{validate_domain, Mailbox}; +use mail_core::model::Domain; use mail_core::store::{AuditRecord, NewDomainRow}; use mail_core::{dkim, dns, CoreError}; +use mail_oci::DomainOnboarding; use serde::Deserialize; use serde_json::{json, Value}; use uuid::Uuid; use crate::auth::{Auth, Capability}; use crate::error::ApiError; +use crate::oci::Oci; use crate::state::AppState; use crate::views; @@ -34,6 +43,10 @@ struct CreateDomain { open_tracking: bool, #[serde(default)] click_tracking: bool, + /// From addresses to approve on the relay right away (optional; every + /// address used later is approved on the next verify). + #[serde(default)] + senders: Vec, } fn validate_label(label: &str, field: &str) -> Result<(), ApiError> { @@ -51,6 +64,17 @@ fn validate_label(label: &str, field: &str) -> Result<(), ApiError> { } } +fn validate_senders(senders: &[String]) -> Result, ApiError> { + senders + .iter() + .map(|s| { + Mailbox::parse(s) + .map(|m| m.address.to_ascii_lowercase()) + .map_err(|e| ApiError::validation(format!("`senders`: {e}"))) + }) + .collect() +} + async fn audit( state: &AppState, auth: &Auth, @@ -72,6 +96,55 @@ async fn audit( Ok(()) } +/// With OCI enabled: onboard the domain and store OCI's record list (ours +/// included) on the row. An OCI failure is logged, not fatal: the customer +/// keeps our records and the next verify retries. +async fn onboard_on_relay( + state: &AppState, + domain: Domain, + senders: &[String], +) -> Result<(Domain, Option), ApiError> { + let Some(oci) = &state.oci else { + return Ok((domain, None)); + }; + match oci.onboard(&domain, senders).await { + Ok(onboarding) => { + let records = Oci::records(&domain, &onboarding); + let updated = state + .store + .update_domain_records(domain.id, &records) + .await?; + tracing::info!(domain = %updated.name, dkim = %onboarding.dkim.lifecycle_state, senders = onboarding.senders.len(), sender_failures = onboarding.sender_failures.len(), "domain onboarded on OCI"); + Ok((updated, Some(onboarding))) + } + Err(e) => { + tracing::warn!(domain = %domain.name, error = %e, "OCI onboarding failed; keeping our own records"); + Ok((domain, None)) + } + } +} + +/// What the relay side knows, for the API response. +fn relay_view(onboarding: Option<&DomainOnboarding>) -> Value { + match onboarding { + None => Value::Null, + Some(ob) => json!({ + "provider": "oci", + "dkim_state": ob.dkim.lifecycle_state, + "dkim_selector": ob.dkim.name, + "senders": ob.senders.iter().map(|s| json!({ "address": s.email_address, "state": s.lifecycle_state })).collect::>(), + "sender_failures": ob.sender_failures.iter().map(|(a, e)| json!({ "address": a, "error": e })).collect::>(), + }), + } +} + +fn with_relay(mut domain_json: Value, onboarding: Option<&DomainOnboarding>) -> Value { + if let Some(obj) = domain_json.as_object_mut() { + obj.insert("relay".into(), relay_view(onboarding)); + } + domain_json +} + async fn create( State(state): State, auth: Auth, @@ -98,6 +171,7 @@ async fn create( .region .clone() .unwrap_or_else(|| "eu-frankfurt-1".into()); + let senders = validate_senders(&body.0.senders)?; let keys = dkim::generate_keypair()?; let selector = state.cfg.dkim_selector.clone(); @@ -118,15 +192,19 @@ async fn create( }) .await?; tracing::info!(domain = %domain.name, id = %domain.id, account = %domain.account_id, "domain created"); + let (domain, onboarding) = onboard_on_relay(&state, domain, &senders).await?; audit( &state, &auth, "domain.created", domain.id, - json!({ "name": domain.name }), + json!({ "name": domain.name, "relay_onboarded": onboarding.is_some() }), ) .await?; - Ok((StatusCode::CREATED, Json(views::domain_full(&domain)))) + Ok(( + StatusCode::CREATED, + Json(with_relay(views::domain_full(&domain), onboarding.as_ref())), + )) } async fn list(State(state): State, auth: Auth) -> Result, ApiError> { @@ -200,7 +278,9 @@ async fn delete( Ok(Json(views::deleted("domain", id))) } -/// Real DNS lookups; the result is persisted and visible on `GET /domains/{id}`. +/// Real DNS lookups (after refreshing the relay onboarding, which also +/// approves every From address the account has used on this domain). The +/// result is persisted and visible on `GET /domains/{id}`. async fn verify( State(state): State, auth: Auth, @@ -208,13 +288,24 @@ async fn verify( ) -> Result, ApiError> { auth.require(Capability::Manage)?; let domain = state.store.account_domain(auth.account_id(), id).await?; + let senders = state.store.from_addresses_for_domain(domain.id).await?; + let (domain, onboarding) = onboard_on_relay(&state, domain, &senders).await?; let outcome = dns::verify_domain(&domain).await.map_err(|e| match e { CoreError::Dns(m) => ApiError::new(StatusCode::SERVICE_UNAVAILABLE, "dns_lookup_failed", m), other => ApiError::from(other), })?; + let mut status = outcome.status; + if state.oci.is_some() && status == dns::STATUS_VERIFIED { + // Our records resolve, but the relay must also be ready to sign. + let relay_ready = onboarding.as_ref().is_some_and(DomainOnboarding::dkim_active); + if !relay_ready { + tracing::info!(domain = %domain.name, "DNS verified but OCI DKIM not ACTIVE yet; keeping pending"); + status = dns::STATUS_PENDING.into(); + } + } let updated = state .store - .update_domain_verification(id, &outcome.status, &outcome.records) + .update_domain_verification(id, &status, &outcome.records) .await?; tracing::info!(domain = %updated.name, status = %updated.status, "domain verification ran"); audit( @@ -222,8 +313,15 @@ async fn verify( &auth, "domain.verified", id, - json!({ "name": updated.name, "status": updated.status }), + json!({ + "name": updated.name, + "status": updated.status, + "relay_dkim": onboarding.as_ref().map(|o| o.dkim.lifecycle_state.clone()), + }), ) .await?; - Ok(Json(views::object_ref("domain", updated.id))) + Ok(Json(with_relay( + views::domain_full(&updated), + onboarding.as_ref(), + ))) } diff --git a/apps/mail/crates/mail-server/src/routes/public.rs b/apps/mail/crates/mail-server/src/routes/public.rs index 3e590421..e2cf2179 100644 --- a/apps/mail/crates/mail-server/src/routes/public.rs +++ b/apps/mail/crates/mail-server/src/routes/public.rs @@ -28,7 +28,17 @@ pub fn router() -> Router { async fn healthz(State(state): State) -> Response { match state.store.ping().await { - Ok(()) => Json(json!({ "ok": true, "service": "scribase-mail" })).into_response(), + Ok(()) => { + let relays = state.relay_pool.as_ref().map(|p| p.health()); + Json(json!({ + "ok": true, + "service": "scribase-mail", + "transport": if relays.is_some() { "relay-pool" } else { "relay" }, + "relays": relays, + "oci_onboarding": state.oci.is_some(), + })) + .into_response() + } Err(e) => { tracing::error!(error = %e, "healthz: database unreachable"); ( diff --git a/apps/mail/crates/mail-server/src/state.rs b/apps/mail/crates/mail-server/src/state.rs index 0a40538d..cd16f1d6 100644 --- a/apps/mail/crates/mail-server/src/state.rs +++ b/apps/mail/crates/mail-server/src/state.rs @@ -7,9 +7,11 @@ use std::sync::{Arc, Mutex}; use std::time::{Duration, Instant}; use mail_core::{CoreConfig, PgStore, SigningSecret}; +use mail_mta::RelayPool; use uuid::Uuid; use crate::jwt::JwtVerifier; +use crate::oci::Oci; #[derive(Clone)] pub struct AppState { @@ -22,6 +24,11 @@ pub struct AppState { /// `From` for invitation emails, on a domain of the system account. pub system_from: Option, pub invite_ttl: Duration, + /// OCI Email Delivery onboarding (`OCI_ONBOARDING=on`); `None` means + /// domains get only our own DKIM/SPF/DMARC records. + pub oci: Option>, + /// The relay pool when `MAIL_TRANSPORT=relay-pool`, for `/healthz`. + pub relay_pool: Option>, } /// In-memory token bucket per caller id (API key id, or account / user id diff --git a/apps/mail/crates/mail-server/src/submit.rs b/apps/mail/crates/mail-server/src/submit.rs new file mode 100644 index 00000000..39d7e638 --- /dev/null +++ b/apps/mail/crates/mail-server/src/submit.rs @@ -0,0 +1,37 @@ +//! SMTP submission (ports 587/465) embedded in the API process. Enabled when +//! `SUBMIT_TLS_CERT` is set; every `SUBMIT_*` variable is documented in +//! `mail-submit/src/config.rs`. Sessions authenticate with +//! `mail_core::authenticate_api_key` and queue through `mail_core::enqueue_raw`. + +use std::sync::Arc; + +use mail_core::{CoreConfig, PgStore}; +use mail_submit::{CoreDeps, SubmitConfig}; + +use crate::env; + +/// Spawn the listeners. Returns the human-readable bind summary when enabled. +pub fn spawn(store: PgStore, cfg: Arc) -> anyhow::Result> { + if env::opt("SUBMIT_TLS_CERT").is_none() { + tracing::info!("SMTP submission disabled (SUBMIT_TLS_CERT unset)"); + return Ok(None); + } + let submit_cfg = SubmitConfig::from_env().map_err(|e| anyhow::anyhow!("submission config: {e}"))?; + let summary = format!( + "starttls={} implicit_tls={}", + submit_cfg + .starttls_addr + .map(|a| a.to_string()) + .unwrap_or_else(|| "off".into()), + submit_cfg + .implicit_tls_addr + .map(|a| a.to_string()) + .unwrap_or_else(|| "off".into()) + ); + tokio::spawn(async move { + if let Err(e) = mail_submit::serve(submit_cfg, CoreDeps { store, cfg }).await { + tracing::error!(error = %e, "SMTP submission stopped"); + } + }); + Ok(Some(summary)) +} diff --git a/apps/mail/crates/mail-server/src/transport.rs b/apps/mail/crates/mail-server/src/transport.rs new file mode 100644 index 00000000..c34d051d --- /dev/null +++ b/apps/mail/crates/mail-server/src/transport.rs @@ -0,0 +1,89 @@ +//! Outbound transport selection (`MAIL_TRANSPORT`). +//! +//! | Value | What runs | +//! |---|---| +//! | `relay-pool` (default) | `mail_mta::RelayPool`: OCI Email Delivery primary + optional secondary/tertiary relays, health probes, failover, per-relay quotas (`RELAY_*`, falls back to `SMTP_*`). | +//! | `relay` | the legacy single lettre smarthost (`SMTP_*`). | +//! | `direct` | our own direct-to-MX MTA. Code-complete in `mail-mta` but parked: no host of ours may use outbound port 25 (owner, 2026-11-13). | + +use std::sync::Arc; + +use anyhow::{bail, Context}; +use mail_core::{RelayTransport, SmtpConfig}; +use mail_mta::RelayPool; +use mail_types::Transport; + +use crate::env; + +/// The transport plus what the rest of the server wants to know about it. +pub struct Outbound { + pub transport: Arc, + /// Set for `relay-pool`, so `/healthz` can report relay health. + pub relay_pool: Option>, + /// Whether a 250 from the transport means `delivered` (final hop) or + /// only `sent` (relay). + pub final_hop: bool, +} + +fn smtp_config() -> anyhow::Result { + let host = env::required("SMTP_HOST")?; + let port = env::or("SMTP_PORT", "587") + .parse::() + .context("SMTP_PORT must be a port number")?; + let tls = !matches!( + std::env::var("SMTP_TLS").ok().as_deref(), + Some("off" | "false" | "0") + ); + let username = env::opt("SMTP_USER"); + let password = env::opt("SMTP_PASS"); + if tls && (username.is_none() || password.is_none()) { + bail!("SMTP_USER and SMTP_PASS must be set for the relay (or SMTP_TLS=off for a local dev sink)"); + } + Ok(SmtpConfig { + host, + port, + username, + password, + tls, + }) +} + +/// Build the transport named by `kind`. Must run inside the tokio runtime +/// (the relay pool spawns its health-check loop). +pub fn build(kind: &str) -> anyhow::Result { + match kind { + "relay-pool" | "relay_pool" | "pool" => { + let pool = Arc::new( + RelayPool::from_env().map_err(|e| anyhow::anyhow!("relay pool: {e}"))?, + ); + let names: Vec = pool.relays().iter().map(|r| r.cfg.to_string()).collect(); + tracing::info!(relays = ?names, "transport = relay-pool"); + let probe = pool.clone(); + tokio::spawn(async move { + let up = probe.probe_all().await; + tracing::info!(up, total = probe.relays().len(), "relay start-up probe"); + }); + pool.spawn_health_checks(); + Ok(Outbound { + transport: pool.clone(), + relay_pool: Some(pool), + final_hop: false, + }) + } + "relay" => { + let cfg = smtp_config()?; + tracing::info!(host = %cfg.host, port = cfg.port, tls = cfg.tls, "transport = relay (lettre STARTTLS smarthost)"); + Ok(Outbound { + transport: Arc::new( + RelayTransport::new(&cfg).map_err(|e| anyhow::anyhow!(e.to_string()))?, + ), + relay_pool: None, + final_hop: false, + }) + } + "direct" => bail!( + "MAIL_TRANSPORT=direct is parked: no host of ours may use outbound port 25 (owner decision 2026-11-13); use relay-pool" + ), + other => bail!("MAIL_TRANSPORT must be `relay-pool`, `relay` or `direct`, got `{other}`"), + } +} diff --git a/apps/mail/crates/mail-submit/Cargo.toml b/apps/mail/crates/mail-submit/Cargo.toml index 78886629..d23d7697 100644 --- a/apps/mail/crates/mail-submit/Cargo.toml +++ b/apps/mail/crates/mail-submit/Cargo.toml @@ -23,9 +23,8 @@ tokio = { version = "1", features = ["rt-multi-thread", "macros", "net", "io-uti tokio-rustls = { version = "0.26", default-features = false, features = ["ring", "tls12", "logging"] } rustls = { version = "0.23", default-features = false, features = ["ring", "tls12", "std", "logging"] } rustls-pemfile = "2" -# SMTP command parsing (MIT OR Apache-2.0) and RFC 5322 / MIME parsing (Apache-2.0 OR MIT). +# SMTP command parsing (MIT OR Apache-2.0). Header handling uses mail-core's parser. smtp-proto = "0.2" -mail-parser = "1.0" sqlx = { version = "0.8", default-features = false, features = ["runtime-tokio-rustls", "postgres"] } base64 = "0.22" uuid = { version = "1", features = ["v4"] } diff --git a/apps/mail/crates/mail-submit/README.md b/apps/mail/crates/mail-submit/README.md index d0ff066e..9427d45b 100644 --- a/apps/mail/crates/mail-submit/README.md +++ b/apps/mail/crates/mail-submit/README.md @@ -61,11 +61,18 @@ All variables: `src/config.rs`. mail-server owns migrations and the delivery workers; this process only authenticates and enqueues. To embed it, call `mail_submit::serve(SubmitConfig, CoreDeps { store, cfg })`. +## What happens to the message + +Since 2026-11-13 submissions go through `mail_core::enqueue_raw`: the bytes +are queued verbatim and the worker only adds our DKIM signature. The client's +`Message-ID`, `To:`/`Cc:` (including header-only addresses), `In-Reply-To`, +`References`, `List-*` and any `X-*` headers are kept. We remove `Bcc`, +`Return-Path`, `Received`, `Delivered-To`, `X-Original-To`, `DKIM-Signature`, +`ARC-*`, `Authentication-Results` and `X-Scribase-Source`, and add `Date` / +`Message-ID` when missing (RFC 6409 §8). The email is tagged `source=smtp`. +Authentication uses `mail_core::authenticate_api_key`, the same lookup as +`Authorization: Bearer`. + ## Known gaps -- The client's `Message-ID` is replaced by ours (mail-core generates it); - `In-Reply-To`/`References` are kept. -- `To:`/`Cc:` header addresses that are not envelope recipients are dropped - from the stored headers (we cannot store a header-only address without - mail-core also delivering to it). - No `CHUNKING`/`BDAT`, no `DSN` parameters. diff --git a/apps/mail/crates/mail-submit/src/core_adapter.rs b/apps/mail/crates/mail-submit/src/core_adapter.rs index dab69217..e9271f0b 100644 --- a/apps/mail/crates/mail-submit/src/core_adapter.rs +++ b/apps/mail/crates/mail-submit/src/core_adapter.rs @@ -1,36 +1,22 @@ -//! The one place this crate touches `mail-core`. If mail-core's key or -//! enqueue API moves again (e.g. a public `authenticate_api_key(pool, raw)`), -//! only this file changes. +//! The one place this crate touches `mail-core`: key authentication, the +//! sender-domain policy check at `MAIL FROM`, and handing the finished +//! message to the queue through `mail_core::enqueue_raw`. use std::sync::Arc; -use mail_core::apikey::{hash_token, KEY_PREFIX}; -use mail_core::enqueue::SendRequest; -use mail_core::{enqueue, Caller, CoreConfig, CoreError, PgStore}; +use mail_core::model::Tag; +use mail_core::{authenticate_api_key, enqueue_raw, CoreConfig, CoreError, PgStore}; use uuid::Uuid; +pub use mail_core::KeyContext; + use crate::error::Reply; -/// What an authenticated SMTP session knows about its API key. -#[derive(Debug, Clone)] -pub struct KeyContext { - pub account_id: Uuid, - pub api_key_id: Uuid, - pub key_name: String, - /// `sending_access` keys bound to one domain may only send from it. - pub restricted_domain: Option, - /// `sk_test_` keys: any From domain, simulated delivery, not metered. - pub test: bool, -} - -impl KeyContext { - pub fn caller(&self) -> Caller { - Caller { - account_id: self.account_id, - api_key_id: Some(self.api_key_id), - restricted_domain: self.restricted_domain.clone(), - test: self.test, - } +/// Tag every SMTP submission carries (`source=smtp`). +pub fn source_tag() -> Tag { + Tag { + name: "source".into(), + value: "smtp".into(), } } @@ -43,38 +29,16 @@ pub struct CoreDeps { impl CoreDeps { /// Verify an `sk_` key exactly like `Authorization: Bearer` does on the - /// HTTP API: SHA-256 of the token looked up among non-revoked keys. + /// HTTP API (shared `mail_core::authenticate_api_key`). pub async fn authenticate_api_key(&self, raw: &str) -> Result, CoreError> { - let token = raw.trim(); - if !token.starts_with(KEY_PREFIX) { - return Ok(None); - } - let Some(key) = self.store.api_key_by_hash(&hash_token(token)).await? else { - return Ok(None); - }; - let restricted_domain = match (key.is_full_access(), key.domain_id) { - (false, Some(domain_id)) => Some(self.store.domain_by_id(domain_id).await?.name), - _ => None, - }; - let store = self.store.clone(); - let key_id = key.id; - tokio::spawn(async move { - if let Err(e) = store.touch_api_key(key_id).await { - tracing::debug!(error = %e, "last_used_at update failed"); - } - }); - Ok(Some(KeyContext { - account_id: key.account_id, - api_key_id: key.id, - key_name: key.name, - restricted_domain, - test: key.is_test, - })) + authenticate_api_key(&self.store, raw).await } /// May this key send from `domain`? Restricted keys: exact match. Test /// keys: anything. Other keys: the domain must be registered to the - /// key's account and verified (or trusted in dev). + /// key's account and verified (or trusted in dev). Checked at `MAIL FROM` + /// so a wrong sender is refused before the client uploads the body; + /// `enqueue_raw` repeats the check on the `From:` header. pub async fn sender_domain_allowed( &self, key: &KeyContext, @@ -93,10 +57,17 @@ impl CoreDeps { }) } - /// Put a parsed message on the normal queue (same DKIM signing, - /// suppression, tracking, webhooks, metering and logs as `POST /emails`). - pub async fn enqueue(&self, key: &KeyContext, req: SendRequest) -> Result { - match enqueue::enqueue(&self.store, &self.cfg, &key.caller(), req).await { + /// Queue the finished RFC 5322 bytes verbatim for the envelope + /// recipients (same DKIM signing, suppression, webhooks, metering and + /// logs as `POST /emails`; the client's `Message-ID` is kept). + pub async fn enqueue( + &self, + key: &KeyContext, + raw: &[u8], + rcpts: &[String], + ) -> Result { + match enqueue_raw(&self.store, &self.cfg, &key.caller(), raw, rcpts, vec![source_tag()]).await + { Ok(email) => Ok(email.id), Err(e) => Err(map_core_error(e)), } diff --git a/apps/mail/crates/mail-submit/src/message.rs b/apps/mail/crates/mail-submit/src/message.rs index a50159e1..e9de93fd 100644 --- a/apps/mail/crates/mail-submit/src/message.rs +++ b/apps/mail/crates/mail-submit/src/message.rs @@ -1,239 +1,138 @@ -//! Turn a submitted RFC 5322 message into the `SendRequest` the core -//! pipeline consumes. The envelope decides who receives the message; the -//! headers decide what they see. +//! Prepare a submitted RFC 5322 message for `mail_core::enqueue_raw`: the +//! bytes go out verbatim (the worker only adds our DKIM signature), so the +//! only edits made here are the ones a submission server must make: drop +//! trace/authentication headers a client has no business asserting, drop +//! `Bcc:`, and add `Date:` / `Message-ID:` when the client left them out +//! (RFC 6409 §8.1–8.2). The envelope decides who receives the message. -use base64::Engine; -use mail_core::enqueue::{AttachmentInput, OneOrMany, SendRequest}; -use mail_core::model::Tag; -use mail_parser::{AddressList, HeaderValue, Message, MessageParser}; +use mail_core::address::Mailbox; +use mail_core::raw::parse_headers; +use mail_core::timefmt::now_rfc2822; use crate::error::Reply; -const B64: base64::engine::GeneralPurpose = base64::engine::general_purpose::STANDARD; - -/// Header fields the core pipeline writes itself (or that must never be -/// forwarded from a submitting client). +/// Header fields removed from every submitted message. const DROPPED_HEADERS: &[&str] = &[ - "from", - "to", - "cc", "bcc", - "reply-to", - "subject", - "date", - "message-id", - "mime-version", - "content-type", - "content-transfer-encoding", - "content-disposition", - "content-id", + "return-path", + "received", + "delivered-to", + "x-original-to", "dkim-signature", "arc-seal", "arc-message-signature", "arc-authentication-results", "authentication-results", - "return-path", - "received", - "list-unsubscribe", - "list-unsubscribe-post", "x-scribase-source", ]; -/// The converted message plus the lowercased From domain for policy checks. -pub struct Converted { - pub request: SendRequest, +/// The sanitized message plus the lowercased `From:` domain for policy checks. +pub struct Prepared { + pub raw: Vec, pub from_domain: String, } -/// Parse and convert. `envelope_rcpts` are the accepted RCPT TO addresses. -pub fn convert(raw: &[u8], envelope_rcpts: &[String]) -> Result { - let message = MessageParser::default() - .parse(raw) - .ok_or_else(|| Reply::message_rejected("Message could not be parsed"))?; +/// Byte offset where the body starts (after the blank line), and the length +/// of that separator, or `None` when the message has no body. +fn split_body(raw: &[u8]) -> (usize, usize) { + if let Some(i) = raw.windows(4).position(|w| w == b"\r\n\r\n") { + return (i + 2, 2); + } + if let Some(i) = raw.windows(2).position(|w| w == b"\n\n") { + return (i + 1, 1); + } + (raw.len(), 0) +} - let from = first_mailbox(message.from()) +/// Group the raw header block into logical fields (first line + folded +/// continuation lines), keeping every byte of each field. +fn logical_fields(block: &[u8]) -> Vec<&[u8]> { + let mut fields: Vec<(usize, usize)> = Vec::new(); + let mut start = 0; + let mut pos = 0; + while pos < block.len() { + let end = block[pos..] + .iter() + .position(|&b| b == b'\n') + .map(|i| pos + i + 1) + .unwrap_or(block.len()); + let continuation = matches!(block[pos], b' ' | b'\t'); + if continuation && !fields.is_empty() { + if let Some(last) = fields.last_mut() { + last.1 = end; + } + } else { + if pos > start { + // Should not happen (every byte belongs to a field), kept for safety. + fields.push((start, pos)); + } + fields.push((pos, end)); + start = end; + } + pos = end; + } + fields.into_iter().map(|(s, e)| &block[s..e]).collect() +} + +fn field_name(field: &[u8]) -> Option { + let colon = field.iter().position(|&b| b == b':')?; + let name = std::str::from_utf8(&field[..colon]).ok()?.trim(); + (!name.is_empty()).then(|| name.to_ascii_lowercase()) +} + +/// Sanitize and complete the message. `envelope_rcpts` is only used to make +/// sure there is something to deliver to; `hostname` names the +/// `Message-ID` we add when the client sent none. +pub fn prepare(raw: &[u8], envelope_rcpts: &[String]) -> Result { + if envelope_rcpts.is_empty() { + return Err(Reply::bad_sequence("RCPT TO required first")); + } + let headers = parse_headers(raw).map_err(|e| Reply::message_rejected(&e.to_string()))?; + let get = |name: &str| { + headers + .iter() + .find(|(n, _)| n.eq_ignore_ascii_case(name)) + .map(|(_, v)| v.as_str()) + }; + let from_raw = get("From") + .filter(|v| !v.trim().is_empty()) .ok_or_else(|| Reply::message_rejected("A From header with one address is required"))?; - let from_domain = from - .rsplit_once('@') - .map(|(_, d)| d.trim_end_matches('>').to_ascii_lowercase()) - .filter(|d| !d.is_empty()) - .ok_or_else(|| Reply::message_rejected("From header address has no domain"))?; - - let (to, cc, bcc) = recipients(&message, envelope_rcpts); - let subject = message - .subject() - .map(str::trim) - .filter(|s| !s.is_empty()) - .unwrap_or("(no subject)") - .to_string(); - let (html, text) = bodies(&message); - if html.is_none() && text.is_none() { - return Err(Reply::message_rejected( - "Message has no text or HTML body", - )); + let from = Mailbox::parse(from_raw) + .map_err(|_| Reply::message_rejected("From header address could not be parsed"))?; + let from_domain = from.domain().to_ascii_lowercase(); + if from_domain.is_empty() { + return Err(Reply::message_rejected("From header address has no domain")); } - let request = SendRequest { - from: Some(from), - to: OneOrMany::Many(to), - cc: OneOrMany::Many(cc), - bcc: OneOrMany::Many(bcc), - reply_to: OneOrMany::Many(mailboxes(message.reply_to())), - subject: Some(subject), - html, - text, - headers: custom_headers(&message), - attachments: attachments(&message), - tags: vec![Tag { - name: "source".into(), - value: "smtp".into(), - }], - scheduled_at: None, - }; - Ok(Converted { - request, + let (body_start, sep_len) = split_body(raw); + let header_block = &raw[..body_start.saturating_sub(sep_len)]; + let body = &raw[body_start..]; + let eol: &[u8] = if header_block.contains(&b'\r') { b"\r\n" } else { b"\n" }; + + let mut out: Vec = Vec::with_capacity(raw.len() + 128); + if get("Date").is_none() { + out.extend_from_slice(format!("Date: {}", now_rfc2822()).as_bytes()); + out.extend_from_slice(eol); + } + if get("Message-ID").is_none() { + out.extend_from_slice( + format!("Message-ID: <{}@{from_domain}>", uuid::Uuid::new_v4()).as_bytes(), + ); + out.extend_from_slice(eol); + } + for field in logical_fields(header_block) { + let dropped = field_name(field).is_some_and(|n| DROPPED_HEADERS.contains(&n.as_str())); + if !dropped { + out.extend_from_slice(field); + } + } + if !out.ends_with(b"\n") { + out.extend_from_slice(eol); + } + out.extend_from_slice(eol); + out.extend_from_slice(body); + Ok(Prepared { + raw: out, from_domain, }) } - -/// `"Name" ` or `addr` for every mailbox in an address header. -fn mailboxes(list: Option>) -> Vec { - list.map(|l| { - l.mailboxes() - .filter_map(|m| { - let addr = m.address()?.trim(); - if addr.is_empty() { - return None; - } - Some(match m.name().map(str::trim).filter(|n| !n.is_empty()) { - Some(name) => format!("{} <{addr}>", quote_name(name)), - None => addr.to_string(), - }) - }) - .collect() - }) - .unwrap_or_default() -} - -fn first_mailbox(list: Option>) -> Option { - mailboxes(list).into_iter().next() -} - -fn quote_name(name: &str) -> String { - let cleaned: String = name - .chars() - .filter(|c| !c.is_control() && *c != '"' && *c != '\\') - .collect(); - format!("\"{cleaned}\"") -} - -fn bare_address(header_mailbox: &str) -> String { - header_mailbox - .rsplit_once('<') - .map(|(_, rest)| rest.trim_end_matches('>')) - .unwrap_or(header_mailbox) - .trim() - .to_ascii_lowercase() -} - -/// Split the envelope into To / Cc (header mailboxes that are also envelope -/// recipients, keeping display names) and Bcc (envelope-only recipients). -/// Header-only addresses are not delivered to: the envelope is authoritative. -fn recipients( - message: &Message<'_>, - envelope: &[String], -) -> (Vec, Vec, Vec) { - let env: Vec = envelope.iter().map(|r| r.to_ascii_lowercase()).collect(); - let in_envelope = |hdr: &String| env.contains(&bare_address(hdr)); - let to: Vec = mailboxes(message.to()).into_iter().filter(in_envelope).collect(); - let cc: Vec = mailboxes(message.cc()).into_iter().filter(in_envelope).collect(); - let covered: Vec = to.iter().chain(&cc).map(|h| bare_address(h)).collect(); - let bcc: Vec = envelope - .iter() - .filter(|r| !covered.contains(&r.to_ascii_lowercase())) - .cloned() - .collect(); - if to.is_empty() { - // No usable To header: address the envelope recipients directly. - return (bcc, cc, Vec::new()); - } - (to, cc, bcc) -} - -/// Only genuine `text/html` / `text/plain` parts count; mail-parser's -/// synthesised alternatives are left to the core builder. -fn bodies(message: &Message<'_>) -> (Option, Option) { - let html = message - .html_body() - .find(|p| p.is_content_type("text", "html")) - .and_then(|p| p.text()) - .map(|c| c.into_owned()) - .filter(|s| !s.trim().is_empty()); - let text = message - .text_body() - .find(|p| p.is_content_type("text", "plain") || p.content_type().is_none()) - .and_then(|p| p.text()) - .map(|c| c.into_owned()) - .filter(|s| !s.trim().is_empty()); - (html, text) -} - -/// Pass through every header the core pipeline does not own, unfolded. -fn custom_headers(message: &Message<'_>) -> serde_json::Map { - let mut out = serde_json::Map::new(); - for header in message.headers().iter() { - let name = header.raw_name().trim(); - if name.is_empty() || DROPPED_HEADERS.contains(&name.to_ascii_lowercase().as_str()) { - continue; - } - if !name.chars().all(|c| c.is_ascii_graphic() && c != ':') { - continue; - } - let value = match header.value() { - HeaderValue::Text(t) => t.to_string(), - _ => String::from_utf8_lossy(header.raw_value()).into_owned(), - }; - let unfolded = unfold(&value); - if unfolded.is_empty() || out.contains_key(name) { - continue; - } - out.insert(name.to_string(), serde_json::Value::String(unfolded)); - } - out -} - -fn unfold(value: &str) -> String { - value - .split(['\r', '\n']) - .map(str::trim) - .filter(|l| !l.is_empty()) - .collect::>() - .join(" ") -} - -fn attachments(message: &Message<'_>) -> Vec { - message - .attachments() - .filter(|p| !p.is_multipart() && !p.is_message()) - .enumerate() - .map(|(i, part)| { - let filename = part - .attachment_name() - .map(str::to_string) - .unwrap_or_else(|| format!("attachment-{}", i + 1)); - let content_type = part.content_type().map(|ct| match ct.subtype() { - Some(sub) => format!("{}/{sub}", ct.ctype()), - None => ct.ctype().to_string(), - }); - AttachmentInput { - filename: Some(filename), - content: Some(B64.encode(part.decoded())), - path: None, - content_type, - cid: part - .content_id() - .map(|c| c.trim_matches(['<', '>']).to_string()), - } - }) - .collect() -} diff --git a/apps/mail/crates/mail-submit/src/session.rs b/apps/mail/crates/mail-submit/src/session.rs index df772ae3..1fe62f20 100644 --- a/apps/mail/crates/mail-submit/src/session.rs +++ b/apps/mail/crates/mail-submit/src/session.rs @@ -311,7 +311,7 @@ where Step::Reply(submit(&body, &rcpts, &key, ctx, peer).await) } -/// Parse, policy-check the From header, enqueue. +/// Sanitize, policy-check the From header, enqueue the bytes verbatim. async fn submit( raw: &[u8], rcpts: &[String], @@ -319,16 +319,16 @@ async fn submit( ctx: &SessionContext, peer: SocketAddr, ) -> Reply { - let converted = match message::convert(raw, rcpts) { - Ok(c) => c, + let prepared = match message::prepare(raw, rcpts) { + Ok(p) => p, Err(r) => return r, }; - match ctx.deps.sender_domain_allowed(key, &converted.from_domain).await { + match ctx.deps.sender_domain_allowed(key, &prepared.from_domain).await { Ok(true) => {} Ok(false) => { return Reply::sender_rejected(&format!( "From header domain {} is not verified for this API key", - converted.from_domain + prepared.from_domain )) } Err(e) => { @@ -336,13 +336,13 @@ async fn submit( return Reply::temp_failure("Temporary failure checking sender domain"); } } - match ctx.deps.enqueue(key, converted.request).await { + match ctx.deps.enqueue(key, &prepared.raw, rcpts).await { Ok(id) => { - tracing::info!(peer = %peer, key = %key.key_name, email = %id, rcpts = rcpts.len(), bytes = raw.len(), "smtp submission accepted"); + tracing::info!(peer = %peer, key = %key.name, email = %id, rcpts = rcpts.len(), bytes = prepared.raw.len(), "smtp submission accepted"); Reply::ok(id.to_string()) } Err(r) => { - tracing::warn!(peer = %peer, key = %key.key_name, code = r.code, reason = %r.text, "smtp submission rejected"); + tracing::warn!(peer = %peer, key = %key.name, code = r.code, reason = %r.text, "smtp submission rejected"); r } } diff --git a/apps/mail/crates/mail-submit/src/session_auth.rs b/apps/mail/crates/mail-submit/src/session_auth.rs index 762c6453..c976cb1c 100644 --- a/apps/mail/crates/mail-submit/src/session_auth.rs +++ b/apps/mail/crates/mail-submit/src/session_auth.rs @@ -66,7 +66,7 @@ async fn verify_credentials( match key { Some(k) => { ctx.limits.record_auth_success(peer.ip()); - tracing::info!(peer = %peer, key = %k.key_name, "smtp auth ok"); + tracing::info!(peer = %peer, key = %k.name, "smtp auth ok"); state.key = Some(k); Step::Reply(Reply::new(235, "2.7.0", "Authentication succeeded")) } diff --git a/apps/mail/crates/mail-types/src/lib.rs b/apps/mail/crates/mail-types/src/lib.rs index 956ff2c1..5e143e26 100644 --- a/apps/mail/crates/mail-types/src/lib.rs +++ b/apps/mail/crates/mail-types/src/lib.rs @@ -57,6 +57,20 @@ pub struct RecipientResult { pub remote_host: Option, } +/// Prefix a relay transport puts on `RecipientResult::message` when the +/// *relay* refused the whole message (unapproved sender, size, content). +/// Such a result is not the recipient's fault: the sending pipeline marks the +/// email `failed` and never suppresses the recipient. +pub const RELAY_REJECTED_PREFIX: &str = "[relay-rejected]"; + +impl RecipientResult { + /// `true` when this result describes a relay-side rejection rather than a + /// recipient outcome (see [`RELAY_REJECTED_PREFIX`]). + pub fn is_relay_rejection(&self) -> bool { + self.message.starts_with(RELAY_REJECTED_PREFIX) + } +} + #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] pub enum DeliveryOutcome { Delivered, diff --git a/apps/mail/docs/content/test-mode.md b/apps/mail/docs/content/test-mode.md index 85c7d708..05d1862e 100644 --- a/apps/mail/docs/content/test-mode.md +++ b/apps/mail/docs/content/test-mode.md @@ -1,34 +1,39 @@ --- title: Test mode nav: Test mode -description: How to test Scribase Mail without sending real email. Test API keys (sm_test_), sandbox recipient addresses that simulate delivery, bounce and complaint, and what works today. +description: How to test Scribase Mail without sending real email. Test API keys (sk_test_), sandbox recipient addresses that simulate delivery, bounce, delay and complaint, and what is metered. --- -Test mode lets you run your whole integration (send, webhooks, suppression) without any message leaving our system. It is being finished alongside the SMTP listener. {soon} +Test mode lets you run your whole integration (send, webhooks, suppression handling) without any message leaving our system. -## What test mode will do +## Test API keys -- **Test API keys** start with `sm_test_`. Every request with a test key is accepted, validated and logged exactly like production, and webhooks fire, but nothing is handed to a mail server. -- **Sandbox recipients** simulate outcomes so you can exercise every webhook branch: +Test keys start with `sk_test_`. Create one with `POST /api-keys` and `{ "name": "ci", "mode": "test" }` (or `mail-server create-key --test` on your own install). Every request made with a test key is accepted, validated and logged exactly like production, and your webhooks fire, but nothing is handed to a mail server: + +- No domain is required: send from any address on `test.scribase.dev`. +- Sends are stored with `"test": true` (visible in `GET /emails` and `GET /emails/{id}`) and go through a simulated transport. +- Test traffic is not metered against your limits; it only bumps the `emails_test` counter in `GET /usage`. +- Test sends never touch the suppression lists, so a simulated bounce cannot block a real customer later. +- Webhook payloads carry `"test": true` at the top level and inside `data`. +- Test keys work on the SMTP submission port too (username `scribase`, password the `sk_test_` key). + +## Sandbox recipients + +Recipients on `test.scribase.dev` (alias: `sandbox.scribase.com`) script the outcome so you can exercise every webhook branch: | Recipient | Result within 5 seconds | |---|---| -| `delivered@sandbox.scribase.com` | `email.sent` then `email.delivered` | -| `bounced@sandbox.scribase.com` | `email.bounced`, address added to the suppression list | -| `complained@sandbox.scribase.com` | `email.complained`, address added to the suppression list | -| `delayed@sandbox.scribase.com` | `email.delivery_delayed`, then `email.delivered` | +| `delivered@test.scribase.dev` | `email.sent` then `email.delivered` | +| `bounced@test.scribase.dev` | `email.bounced` (550 5.1.1); `last_event` becomes `bounced` | +| `soft-bounce@test.scribase.dev` (alias `delayed@`) | `email.delivery_delayed` (451), then `email.delivered` after the retry | +| `complained@test.scribase.dev` | `email.delivered`, then `email.complained` | +| `suppressed@test.scribase.dev` | `email.suppressed`; nothing is sent | -- Test sends appear in `GET /emails` with `last_event` set as above, so your dashboard and reconciliation code see realistic data. -- Test mode traffic does not count toward your monthly quota. +Any other recipient with a test key behaves like `delivered@`. -## How to test today +## Rehearsing the bounce path on a real message -Until test keys ship, use a real `sending_access` key restricted to a verified domain and send to your own inbox. Everything else below already works: - -- **Validation without sending**: `POST /emails` with a `from` on an unverified domain returns `403 validation_error` after the full body validation has run, so malformed payloads fail with the real `422` messages first. -- **Idempotency**: reuse an `Idempotency-Key` to check that your retry logic receives the same `id`. -- **Webhooks**: create an endpoint with `POST /webhooks`, send one email, verify the signature with [`webhooks.verify`](../webhooks/). Reporting `POST /emails/{id}/events` with `{ "type": "bounced" }` from a full-access key triggers `email.bounced` and the suppression, so you can rehearse the bounce path on a real message to yourself. -- **Auth flows**: the auth endpoints always answer `200` to well-formed requests, so you can drive sign-up pages against a real project with your own address. +With a live full-access key you can also report `POST /emails/{id}/events` with `{ "type": "bounced" }` (or `complained`, `delivered`, `delayed`) on a message you sent to yourself. That triggers the same `email.bounced` webhook and suppression as a real DSN, which is how the inbound bounce pipeline reports asynchronous bounces internally. ## Local development