caelum0x 173b60097d feat(mail): OCI relay pool, direct MTA (parked), inbound HTTPS ingest, Cloudflare inbound forwarder
- mail-oci: OCI Email Delivery client (signed REST), per-customer domain/DKIM/sender onboarding, suppression mirror, sending limits
- mail-mta: RelayPool transport with OCI primary, optional secondary, health/back-off/quota failover; direct MTA kept but off
- mail-inbound: DSN/ARF/DMARC/TLS-RPT parsing + HMAC-signed POST /inbound/raw ingest (no port 25)
- workers/inbound-forwarder: Cloudflare Email Routing worker forwarding raw mail over HTTPS

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

117 lines
5.7 KiB
Rust

//! Posts the same hand-written reports as the SMTP `feed` example to the
//! HTTPS ingest, with valid and invalid signatures, and checks the statuses.
//!
//! ```sh
//! INBOUND_HTTP_SECRET=<same as server> FEED_HTTP=127.0.0.1:8585 FEED_DOMAIN=dev.test \
//! cargo run -p mail-inbound --example ingest_feed
//! ```
#[path = "feed/samples.rs"]
mod samples;
use std::time::Duration;
use mail_inbound::ingest::auth::{self, now_unix};
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::net::TcpStream;
struct Reply {
status: u16,
body: String,
}
/// Minimal HTTP/1.1 POST (Connection: close) so the example needs no HTTP client crate.
async fn post(addr: &str, path: &str, headers: &[(&str, &str)], body: &[u8]) -> Result<Reply, Box<dyn std::error::Error>> {
let mut stream = tokio::time::timeout(Duration::from_secs(5), TcpStream::connect(addr)).await??;
let mut req = format!("POST {path} HTTP/1.1\r\nHost: {addr}\r\nConnection: close\r\nContent-Type: message/rfc822\r\nContent-Length: {}\r\n", body.len());
for (k, v) in headers {
req.push_str(&format!("{k}: {v}\r\n"));
}
req.push_str("\r\n");
stream.write_all(req.as_bytes()).await?;
stream.write_all(body).await?;
let mut raw = Vec::new();
tokio::time::timeout(Duration::from_secs(30), stream.read_to_end(&mut raw)).await??;
let text = String::from_utf8_lossy(&raw).to_string();
let status = text.get(9..12).and_then(|s| s.parse().ok()).unwrap_or(0);
let body = text.split_once("\r\n\r\n").map(|(_, b)| b.to_owned()).unwrap_or_default();
Ok(Reply { status, body })
}
fn check(label: &str, reply: &Reply, expect: u16) -> bool {
let ok = reply.status == expect;
println!("[{}] {label}: expected {expect}, got {} {}", if ok { "PASS" } else { "FAIL" }, reply.status, reply.body.trim());
ok
}
struct Feeder {
addr: String,
secret: String,
}
impl Feeder {
async fn signed(&self, from: &str, to: &str, body: &[u8], ts: i64, tamper: bool) -> Result<Reply, Box<dyn std::error::Error>> {
let ts = ts.to_string();
let mut sig = auth::sign(&self.secret, &ts, from, to, body)?;
if tamper {
// Flip the last hex digit.
let last = sig.pop().unwrap_or('0');
sig.push(if last == '0' { '1' } else { '0' });
}
post(
&self.addr,
"/inbound/raw",
&[
(auth::HEADER_TIMESTAMP, &ts),
(auth::HEADER_FROM, from),
(auth::HEADER_TO, to),
(auth::HEADER_SIGNATURE, &sig),
],
body,
)
.await
}
}
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let addr = std::env::var("FEED_HTTP").unwrap_or_else(|_| "127.0.0.1:8585".into());
let domain = std::env::var("FEED_DOMAIN").unwrap_or_else(|_| "dev.test".into());
let reports_domain = std::env::var("FEED_REPORTS_DOMAIN").unwrap_or_else(|_| format!("reports.{domain}"));
let secret = std::env::var("INBOUND_HTTP_SECRET").map_err(|_| "INBOUND_HTTP_SECRET must be set")?;
let f = Feeder { addr: addr.clone(), secret };
let mut all_ok = true;
let health = post(&addr, "/inbound/healthz", &[], b"").await?;
all_ok &= check("GET-less POST to healthz (method not allowed)", &health, 405);
let now = now_unix();
let dsn = samples::dsn(&domain);
all_ok &= check("RFC 3464 DSN to bounces+abc", &f.signed("", &format!("bounces+abc@{domain}"), &dsn, now, false).await?, 202);
let arf = samples::arf(&domain);
all_ok &= check("ARF complaint to abuse@", &f.signed("feedback@isp.example", &format!("abuse@{domain}"), &arf, now, false).await?, 202);
let dmarc = samples::dmarc_gzip(&domain);
all_ok &= check("DMARC aggregate (gzip XML) to dmarc@", &f.signed("noreply-dmarc-support@google.com", &format!("dmarc@{domain}"), &dmarc, now, false).await?, 202);
let tlsrpt = samples::tlsrpt(&domain);
all_ok &= check("TLS-RPT JSON to tls-rpt@", &f.signed("tlsrpt@google.com", &format!("tls-rpt@{domain}"), &tlsrpt, now, false).await?, 202);
let plain = samples::plain_bounce(&domain);
all_ok &= check("non-RFC3464 bounce to bounces+xyz", &f.signed("mailer-daemon@legacy.example", &format!("bounces+xyz@{domain}"), &plain, now, false).await?, 202);
all_ok &= check("bad HMAC", &f.signed("", &format!("bounces+abc@{domain}"), &dsn, now, true).await?, 401);
all_ok &= check("stale timestamp (-15 min)", &f.signed("", &format!("bounces+abc@{domain}"), &dsn, now - 900, false).await?, 401);
all_ok &= check("future timestamp (+15 min)", &f.signed("", &format!("bounces+abc@{domain}"), &dsn, now + 900, false).await?, 401);
let replay_body = samples::dsn(&domain);
let first = f.signed("", &format!("bounces+replay@{domain}"), &replay_body, now, false).await?;
all_ok &= check("replay: first use", &first, 202);
let second = f.signed("", &format!("bounces+replay@{domain}"), &replay_body, now, false).await?;
all_ok &= check("replay: same signature again", &second, 401);
all_ok &= check("relay attempt to gmail.com", &f.signed("someone@evil.example", "victim@gmail.com", b"Subject: relay\r\n\r\nx", now, false).await?, 403);
all_ok &= check("unknown user on report-only domain", &f.signed("someone@evil.example", &format!("nobody@{reports_domain}"), b"Subject: x\r\n\r\nx", now, false).await?, 404);
all_ok &= check("dmarc@ on report-only domain", &f.signed("a@b.example", &format!("dmarc@{reports_domain}"), &dmarc, now, false).await?, 202);
let unsigned = post(&addr, "/inbound/raw", &[(auth::HEADER_TO, &format!("dmarc@{domain}"))], &dmarc).await?;
all_ok &= check("missing signature headers", &unsigned, 401);
println!("{}", if all_ok { "ALL PASS" } else { "SOME FAILED" });
Ok(())
}