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

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

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

127 lines
9.2 KiB
Markdown

# mail-oci
OCI Email Delivery control plane for Scribase Mail. Talks to the public OCI
REST API directly (there is no official Rust SDK) with draft-cavage HTTP
signatures implemented on `rsa` + `sha2` + `base64`.
Independent implementation, written without reference to useSend source.
Licence: MIT (workspace).
## Why this crate exists
Owner decision 2026-11-13: no host will ever give us outbound port 25, so
every message leaves through **OCI Email Delivery** (`smtp.email.<region>.oci.oraclecloud.com:587`,
STARTTLS, SMTP credentials). OCI only relays mail whose From address is an
**approved sender** inside an **email domain** that has an active **DKIM**
key. For a multi-tenant product that means: whenever a customer adds a domain
with us, we must also create those three things on OCI and tell the customer
which DNS records to publish. This crate does exactly that.
## What it does
| 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. `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.<domain>")` | `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. |
| `get_sending_limits()` | Limits API `GET /20190729/limitValues?serviceName=email-delivery` | Email Delivery has no quota endpoint of its own; the numbers live in the Limits service. Raw rows are returned verbatim plus best-effort picks (`max-emails-day`, `sendrate`, `max-message-size`, `approved-sender-count`, `email-domain-count`). |
| `get_email_configuration()` | `GET /configuration` | Tenancy SMTP (`smtp.email.<region>…`) and HTTP (`cell0.submit.email.<region>…`) submission endpoints. |
| `onboard_domain(...)` | all of the above | The one call the product makes when a customer verifies a domain. Returns `DomainOnboarding` with states and the DNS records to show. |
The HTTP submit endpoint (`POST /20220926/actions/submitEmail`) is
deliberately not used: the relay pool speaks SMTP so DKIM-signed raw MIME
goes out byte-for-byte.
## Configuration
Environment first, `~/.oci/config` second (so the owner's CLI config works unchanged):
| Variable | Fallback | Meaning |
|---|---|---|
| `OCI_TENANCY` | `tenancy` | Tenancy OCID (also the compartment for suppressions). |
| `OCI_USER` | `user` | User OCID that owns the API key. |
| `OCI_FINGERPRINT` | `fingerprint` | API key fingerprint. |
| `OCI_KEY_FILE` | `key_file` | PEM private key (PKCS#8 or PKCS#1). Trailing `OCI_API_KEY` marker tolerated. Never logged. |
| `OCI_REGION` | `region` | e.g. `eu-frankfurt-1`. |
| `OCI_COMPARTMENT` | = tenancy | Compartment for email domains and senders. |
| `OCI_CONFIG_FILE`, `OCI_PROFILE` | `~/.oci/config`, `DEFAULT` | Where the fallback values come from. |
Signing: `Signature version="1",keyId="<tenancy>/<user>/<fingerprint>",algorithm="rsa-sha256",headers="date (request-target) host [content-length content-type x-content-sha256]"`. Clock skew over 5 minutes → 401.
## Verified against the real tenancy (2026-11-13, read-only)
`cargo run -p mail-oci --example inspect` with `~/.oci/config`, region
`eu-frankfurt-1`:
- control plane `ctrl.email.eu-frankfurt-1.oci.oraclecloud.com`; configuration returned `smtp_submit=smtp.email.eu-frankfurt-1.oci.oraclecloud.com`, `http_submit=cell0.submit.email.eu-frankfurt-1.oci.oraclecloud.com`.
- **7 email domains**, all `ACTIVE` with an active DKIM: `scribase.com` (selector `scribase-fra-20260926`, CNAME `scribase-fra-20260926._domainkey.scribase.com → scribase-fra-20260926.scribase.com.dkim.fra1.oracleemaildelivery.com`), `menivor.com`, `mail.menivor.com`, `mail.oxhanatelier.com`, `mail.bidstage.app`, `ereboslab.com`, `vcpeer.com`. `domainVerificationStatus` is unset on all (OCI did not require it for these). The custom return path `bounce.scribase.com` on scribase.com is in state **FAILED** (owner item: delete and recreate, then publish its CNAME).
- **19 approved senders**, all `ACTIVE` (6 on scribase.com: `onboarding@`, `postmaster@`, `hello@`, `arhan@`, `support@`, `no-reply@`).
- **48 suppressions** (HARDBOUNCE + UNSUBSCRIBE), mirrored into `MemoryMirror` with 0 failures.
- Limits (REGION scope): `max-emails-day = 50 000`, `sendrate = 18 000` per minute, `max-message-size = 2 008 192` bytes, `approved-sender-count = 10 000`, `email-domain-count = 10 000`, `email-recipient-domain-count = 1 000`, IP pool / config counts 1 000.
No create or delete call was made against production.
## How it fits the multi-tenant product
When a customer adds `example.com` and clicks verify:
1. `mail-core` generates our own DKIM key (selector `scribase1`) as today.
2. `mail-oci::onboard_domain(client, "example.com", "scribase-fra-<date>", &[their From addresses], Some("bounce"), Some(("scribase1", our_txt)), "dmarc@example.com")`.
3. We show the customer every record in `DomainOnboarding.dns.records`:
- `CNAME <selector>._domainkey.example.com → <selector>.example.com.dkim.fra1.oracleemaildelivery.com` (OCI DKIM)
- `TXT scribase1._domainkey.example.com → v=DKIM1; k=rsa; p=…` (our DKIM)
- `TXT example.com → v=spf1 include:eu.rp.oracleemaildelivery.com ~all` (Frankfurt is in Oracle's EU group; Americas use `rp.oracleemaildelivery.com`, Asia-Pacific `ap.rp.oracleemaildelivery.com`; `spf_include_for_region` picks it)
- `CNAME bounce.example.com → …` when a custom return path was created
- `TXT _dmarc.example.com → v=DMARC1; p=none; rua=mailto:dmarc@example.com; fo=1` — the `rua` points at our inbound (`dmarc@` on the customer domain, or our collector domain) so the DMARC aggregate parser in `mail-inbound` sees the reports.
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`.
## Should we still sign with our own DKIM key as well as OCI's?
**Yes, keep both signatures.** RFC 6376 allows multiple `DKIM-Signature`
headers and DMARC passes if any aligned one verifies.
- OCI's signature is what makes the relay path trustworthy today and it is
tied to the OCI selector the customer publishes.
- Our signature is relay-independent: the same message verifies if it goes out
through the secondary relay or, one day, our own MTA, without the customer
changing DNS again. It also lets us prove authorship of what we handed to
OCI (OCI adds trace headers but does not touch the signed headers or body).
- Cost is one extra header (~400 bytes) and one RSA signature per message.
The one thing to avoid is signing `Return-Path`/`Received`, which OCI rewrites; `mail-core` already signs only the stable headers.
## Relay-side facts the pool depends on
- The relay rewrites MAIL FROM to its own return path, so DSNs land in OCI's
suppression list, not in our VERP mailbox — hence `sync_suppressions`.
- Hard limits: 2 008 192 bytes per message, 50 000 "emails" per day (an
email = one 2 MB chunk per recipient), 18 000 submissions per minute.
## Running
```sh
cargo run -p mail-oci --example inspect # read-only inventory, real tenancy
```
## Dependencies and licences
| Crate | Licence |
|---|---|
| tokio, reqwest, serde, serde_json, thiserror, async-trait, chrono, tracing, base64, percent-encoding, sha2 | MIT OR Apache-2.0 |
| rsa | MIT OR Apache-2.0 |
| rustls (via reqwest `rustls-tls`) | Apache-2.0 OR ISC OR MIT |