diff --git a/CHANGELOG.md b/CHANGELOG.md index 8c8978c..6c9df5e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,14 @@ +## [Unreleased] + +### Fixed + +* **Mailgun: a template deleted at Mailgun is no longer logged as sent.** Mailgun accepts a send that names a template it does not have (200 "Queued") and drops the message afterwards (event `failed`, delivery-status 621 "Template not found", retried every 10 minutes). Before a template send MagicMail now checks the template at Mailgun (`GET /v3/{domain}/templates/{name}?active=yes`, account-level templates `GET /v4/templates/{name}?active=yes`). A deleted template, or one without an active version, fails with `MAGIC_MAIL_PROVIDER_TEMPLATE_UNAVAILABLE` before any message is sent: another account that still has the template sends instead, else the configured Magic Mail fallback template, else the error is returned and the delivery log row is `failed`. A successful check is cached for 60 seconds per account and template (one extra request per template and minute for bulk sends, parallel sends share one check). If the check itself fails (network, timeout, 401/403, 429, 5xx), the send goes ahead and a warning is logged. +* **Mailgun webhooks: ESP blocks and soft bounces no longer suppress the recipient.** A permanent failure with reason `espblock` (the recipient's provider refused the sender, for example `550 5.7.40`) is now recorded as **Blocked** and never added to the suppression list; Mailgun itself does not put such addresses on its bounce list. A permanent failure that Mailgun classifies as `bounce-type: soft` is still recorded as **Bounced** but not suppressed. Only permanent hard bounces suppress, as before. Template-not-found failures (code 621) get the reason code `MAILGUN_TEMPLATE_NOT_FOUND` (Deferred while Mailgun retries, Failed when final) and never suppress. + +### Migration + +* Nothing to do. Mailgun template sends make one extra read request per template and minute; the API key needs read access to templates, which provider-template sync already requires. Addresses suppressed earlier because of a Mailgun `espblock` can be removed under **Plugin Settings → Bounces and recipient checks → Suppressed recipients** (source `mailgun`, reason code `MAILGUN_ESPBLOCK_*`). + # [4.9.0](https://github.com/Schero94/Magic-Mail/compare/v4.8.0...v4.9.0) (2026-11-19) diff --git a/docs/acceptance/2026-11-17-provider-templates.md b/docs/acceptance/2026-11-17-provider-templates.md index ddafe4b..3f9032a 100644 --- a/docs/acceptance/2026-11-17-provider-templates.md +++ b/docs/acceptance/2026-11-17-provider-templates.md @@ -2,7 +2,7 @@ Branch `feat/provider-templates` (PR #20) against `main`. It was developed stacked on `fix/provider-send-paths` (PR #23, SendGrid EU region and safer SendGrid/Mailgun send paths), which shipped as 4.7.0; #20 was then re-applied on top of 4.7.0. Planned release: 4.8.0. -**Status: SendGrid accepted, Mailgun spec-verified only.** On 2026-11-18 every SendGrid check passed against the real SendGrid API (sends in sandbox mode only) and the Event Webhook was tested end to end; see [Live suite](#live-suite) and [SendGrid full integration](#sendgrid-full-integration-2026-11-18). Mailgun has not run against the real API yet (no Mailgun credentials); it is verified against the official OpenAPI specification and with tests. On 2026-11-19 the maintainer approved releasing on this basis; #23 shipped as 4.7.0 and this branch was re-applied on top of it (StrictMode admin tests for the provider-template screens added). The SendGrid live suite passed again on the re-applied branch (48 tests, 30 passed, 0 failed, 18 skipped; account clean afterwards). +**Status: SendGrid accepted, Mailgun spec-verified only.** (Update 2026-11-19: Mailgun has since run against the real API, see [Mailgun live acceptance](./2026-11-19-mailgun-live.md).) On 2026-11-18 every SendGrid check passed against the real SendGrid API (sends in sandbox mode only) and the Event Webhook was tested end to end; see [Live suite](#live-suite) and [SendGrid full integration](#sendgrid-full-integration-2026-11-18). Mailgun has not run against the real API yet (no Mailgun credentials); it is verified against the official OpenAPI specification and with tests. On 2026-11-19 the maintainer approved releasing on this basis; #23 shipped as 4.7.0 and this branch was re-applied on top of it (StrictMode admin tests for the provider-template screens added). The SendGrid live suite passed again on the re-applied branch (48 tests, 30 passed, 0 failed, 18 skipped; account clean afterwards). ## Scope diff --git a/docs/acceptance/2026-11-19-mailgun-live.md b/docs/acceptance/2026-11-19-mailgun-live.md new file mode 100644 index 0000000..7bbdc2b --- /dev/null +++ b/docs/acceptance/2026-11-19-mailgun-live.md @@ -0,0 +1,70 @@ +# Acceptance: Mailgun against the real API (2026-11-19) + +Branch `fix/mailgun-template-preflight` against `main` (4.9.0). Real Mailgun account, US region (`api.mailgun.net`), one sandbox sending domain, one authorized sandbox recipient (the maintainer's own inbox). Credentials only from `~/.config/magic-mail-live/.env`, never printed; every log and request record below is masked (domain, keys, addresses). + +**Status: Mailgun sending, provider templates and the Mailgun webhook accepted against the real API**, with the open points listed under [Not proven live](#not-proven-live). + +## 1. Mailgun accepts a send with a template it does not have + +Observed on the real API before the fix (4.9.0 send path): + +| Step | Result | +| ------------------------------------------------------------------------------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `POST /v3/{domain}/messages` with `template=` | `200 {"message":"Queued"}`; Magic Mail 4.9.0 logs the mail as **Sent** | +| same in test mode (`o:testmode=yes`) | event `delivered`, code 650 "Delivered in test mode" (the template is not evaluated) | +| same without test mode | event `failed`, `severity: temporary`, `reason: generic`, delivery-status code **621** "Template not found", `retry-seconds: 600`, retried every 10 minutes (attempts 1, 2, 3 seen) | +| `GET /v3/{domain}/templates/{name}?active=yes` and `GET /v4/templates/{name}?active=yes`, unknown name | `404 {"message":"template not found"}` (both scopes) | +| `GET /v3/{domain}/templates/{name}?active=yes` for a template created without a version | `200` with `template` but **no `version`** | + +Docs: [Mailgun templates API](https://documentation.mailgun.com/docs/mailgun/api-reference/send/mailgun/templates) and the OpenAPI bundle behind it (`GET /v3/{domain_name}/templates/{template_name}` and `GET /v4/templates/{template_name}`, path parameter is the template **name**, query `active`, responses 200/401/404/500), retrieved 2026-11-19. The docs do not say what `active` returns for a template without a version; the live answer above is the evidence. + +Fix: `sendViaMailgun` checks the template before a template send (`utils/provider-api.js` `checkMailgunTemplate`, 5 s timeout, fixed hosts only). 404 or no active version → `MAGIC_MAIL_PROVIDER_TEMPLATE_UNAVAILABLE` before any message request (pre-dispatch: the next account with the template may send; fallback-safe: the configured local fallback template applies). Positive results are cached 60 s per account, region, domain, scope and template; parallel sends share one check. Network, timeout, 401/403, 429 and 5xx of the check log a warning and the send goes ahead. + +## 2. Live suite + +`set -a; . ~/.config/magic-mail-live/.env; set +a; LIVE_PROVIDERS=mailgun npm run test:live` + +| Code | Result | +| ------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `main` 4.9.0 | 15 Mailgun tests, **14 passed, 1 failed**: the ghost-template assertion expected a 4xx from Mailgun and got `200 Queued` | +| this branch (final) | 63 tests, **15 passed, 0 failed**, 48 skipped (other providers not selected, no EU domain). The ghost template now fails with `MAGIC_MAIL_PROVIDER_TEMPLATE_UNAVAILABLE`, no `messages` request is sent, and the real check answered 404 | + +All live-suite sends run with `o:testmode=yes`. The output contains no key, domain or address (checked with a literal search for each value). + +## 3. Webhook end to end + +Setup: + +- Strapi 5.63.0 (JavaScript app, SQLite, admin panel off) with this branch's `npm run build` output, created under the plugin checkout for the run and deleted afterwards. One Mailgun account with the real API key and the real HTTP webhook signing key; **Block hard-bounced recipients** on. +- A local filter proxy forwarded only `POST /api/magic-mail/webhooks/mailgun/` and answered 404 to everything else. A `cloudflared` quick tunnel pointed at the proxy. +- Before any change, `GET /v3/domains/{domain}/webhooks` (`{"webhooks":{}}`) and `GET /v1/webhooks` (account-level, `{"webhooks":[]}`) were saved. Then `POST /v3/domains/{domain}/webhooks` created `delivered`, `permanent_fail` and `temporary_fail` with the tunnel URL (200 each). + +| Check | Result | +| ---------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| unsigned POST, locally and through the tunnel | 401 | +| any other path or method through the tunnel | 404 (proxy) | +| real send with a deleted template through the fixed send path | `MAGIC_MAIL_PROVIDER_TEMPLATE_UNAVAILABLE`, no `messages` request, email log **failed** | +| real send (no test mode) with a deleted template, pre-send check switched off to reproduce 4.9.0 | Mailgun `200 Queued`; real signed `temporary_fail` webhook (code 621) within 1 s → **200**, signature verified with the signing key, email log **Deferred**, no suppression | +| the same message's Mailgun retry 10 minutes later, after the host was rebuilt with the new webhook mapping | real signed webhook → **200**, email log **Deferred** with the new code `MAILGUN_TEMPLATE_NOT_FOUND`, a second email event, no suppression | +| real 621 retry of an earlier probe message without `magicmail_id` | 200, counted as unmatched, nothing changed | +| real signed webhook re-posted unchanged | 200, nothing processed twice (still one email event) | +| real webhook with the `signature` changed in one character | **401** | +| real webhook with the `token` changed in one character | **401** | +| real webhook with the `signature` object removed | **401** | +| test-mode template send through the host | real signed `delivered` webhook (code 650, `is-test-mode: true`) → 200, email log `deliveryConfirmedAt` set, status stays **Sent** | +| test-mode sends of the live suite (no log in this host) | 5 signed `delivered` webhooks → 200, unmatched | +| real template send to the authorized recipient | Mailgun `failed`, `severity: permanent`, `reason: espblock`, `550 5.7.40` (the recipient's provider refused the sandbox sender), `delivery-status.bounce-type: soft`; Mailgun did **not** add the address to its bounce list (`GET /v3/{domain}/bounces/
` → 404) | + +The `espblock` result exposed a webhook bug: 4.9.0 maps every permanent Mailgun failure except `suppress-*` and `old` to a hard bounce and, with **Block hard-bounced recipients** on, suppresses the address, so one ESP block would have blocked the recipient on every account. Now: `espblock` → **Blocked**, never suppressed; `bounce-type: soft` → **Bounced** but not suppressed; code 621 → `MAILGUN_TEMPLATE_NOT_FOUND` (Deferred while temporary, Failed when permanent), never suppressed. Covered by `tests/webhook-outcomes.test.js` "Mailgun severity and bounce type: only permanent hard bounces suppress" with the payload shapes observed here (fails on 4.9.0). + +Real sends without test mode: 2 (the deleted-template send, not delivered; one template send, refused by the recipient's provider). Subjects were "Magic Mail live test (can be deleted)". + +Teardown: the three domain webhooks deleted (200 each); `GET /v3/domains/{domain}/webhooks` and `GET /v1/webhooks` afterwards are byte-identical to the saved responses. Tunnel, proxy and host stopped; host `.env`, SQLite database and captured bodies deleted. The domain's templates are unchanged (only the synthetic `MAILGUN_TEMPLATE`); a version-less template created to observe the `active=yes` answer was deleted right away. + +## Not proven live + +- **The `permanent_fail` webhook.** Mailgun recorded the `espblock` permanent failure, but no `permanent_fail` post reached the tunnel within 10 minutes, while `temporary_fail` and `delivered` posts did. The cause is unknown. The permanent mapping is covered by tests with the observed event shape only. A hard bounce (`bounce-type: hard`) could not be produced: a sandbox domain only sends to authorized recipients. +- **The final event after Mailgun stops retrying a 621.** Mailgun retried every 600 s; the run ended before Mailgun gave up. The final permanent event is expected to carry reason `old` (never suppressed); with code 621 it is mapped to Failed either way. +- **The first two test-mode sends**, about 15 s after the webhooks were created, produced no webhook; every later test-mode send did. Treat the first seconds after creating a Mailgun webhook as unreliable. +- **Account-level templates** (`/v4/templates/{name}`): the account has none; the live 404 for an unknown name is the only live evidence. The 200 path is covered by the fake-server tests. +- **EU region**: no EU domain configured. diff --git a/docs/delivery.md b/docs/delivery.md index e8873ce..4eb72f6 100644 --- a/docs/delivery.md +++ b/docs/delivery.md @@ -60,30 +60,30 @@ Every SNS message is verified before anything is read: the `TopicArn` must equal **What happens.** Every request is verified with the provider signature (SendGrid ECDSA over the raw body, Mailgun HMAC-SHA256) and a one-hour timestamp window; replays are ignored. Request bodies up to 1 MiB are accepted (SendGrid posts batches of up to 768 KB; change it with [`webhooks.maxBodyBytes`](./configuration.md#plugin-config)); larger ones get `413`. Every event of a batch is processed in the order of the provider timestamps. -| Provider event | Email log | Event (`strapi.eventHub`) | -| ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------ | ---------------------------------- | -| SendGrid `bounce` (type `bounce`), SendGrid `dropped` with reason `Bounced Address` or `Invalid`, Mailgun `failed` + `permanent` | **Bounced**, `bounced: true`, code such as `SENDGRID_BOUNCE_500`, `SENDGRID_DROPPED_INVALID`, `MAILGUN_BOUNCE_550` | `magic-mail.delivery.bounced` | -| SendGrid `bounce` with type `blocked` (a block, not a bad address; SendGrid does not document a retry) | final status `blocked`, shown as **Failed** with `SENDGRID_BLOCKED_x00`; `bounced` stays false | `magic-mail.delivery.blocked` | -| SendGrid `dropped` for a sender-side reason (`Invalid SMTPAPI header`, `Invalid Template`, `Template Render Failure`, `Domain is not allowed`, `Expired`, or an unknown reason) | **Failed**, code `SENDGRID_DROPPED_` (unknown reasons: `SENDGRID_DROPPED_OTHER`) | `magic-mail.delivery.dropped` | -| SendGrid `spamreport`, SendGrid `dropped` with reason `Spam Reporting Address`, Mailgun `complained` | `complained: true` (a drop also sets **Failed**) | `magic-mail.delivery.complained` | -| SendGrid `unsubscribe` / `group_unsubscribe`, SendGrid `dropped` with reason `Unsubscribed Address` / `Group Unsubscribe`, Mailgun `unsubscribed` | `unsubscribed: true`, `unsubscribedAt` (a drop also sets **Failed**) | `magic-mail.delivery.unsubscribed` | -| SendGrid `group_resubscribe` | `unsubscribed: false` (only when newer than the unsubscribe) | `magic-mail.delivery.resubscribed` | -| SendGrid `deferred`, Mailgun `failed` + `temporary` | **Deferred**, code such as `MAILGUN_DEFERRED_421` | `magic-mail.delivery.deferred` | -| SendGrid `delivered`, Mailgun `delivered` | `deliveryConfirmedAt` set; a **Deferred** mail returns to **Sent** | `magic-mail.delivery.delivered` | -| Brevo `hard_bounce` and `invalid_email`, SES `Bounce` with type `Permanent` | **Bounced** (suppressible), code such as `BREVO_HARD_BOUNCE`, `SES_BOUNCE_GENERAL` (SES bounce subtype) | `magic-mail.delivery.bounced` | -| Brevo `soft_bounce` and `deferred`, SES `DeliveryDelay` | **Deferred** | `magic-mail.delivery.deferred` | -| Brevo `blocked`, SES `Bounce` with type `Transient` or `Undetermined` (SES publishes these only after it stopped retrying) | final status `blocked`, not suppressed | `magic-mail.delivery.blocked` | -| Brevo `error`, SES `Reject` and `Rendering Failure` | **Failed** | `magic-mail.delivery.dropped` | -| Brevo `spam`, SES `Complaint` | `complained: true` | `magic-mail.delivery.complained` | -| Brevo `unsubscribed`, SES `Subscription` (unsubscribe) | `unsubscribed: true` | `magic-mail.delivery.unsubscribed` | -| Brevo `delivered`, SES `Delivery` | `deliveryConfirmedAt` set | `magic-mail.delivery.delivered` | +| Provider event | Email log | Event (`strapi.eventHub`) | +| -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------ | ---------------------------------- | +| SendGrid `bounce` (type `bounce`), SendGrid `dropped` with reason `Bounced Address` or `Invalid`, Mailgun `failed` + `permanent` (except the two rows below) | **Bounced**, `bounced: true`, code such as `SENDGRID_BOUNCE_500`, `SENDGRID_DROPPED_INVALID`, `MAILGUN_BOUNCE_550` | `magic-mail.delivery.bounced` | +| SendGrid `bounce` with type `blocked` (a block, not a bad address; SendGrid does not document a retry), Mailgun `failed` + `permanent` with reason `espblock` (code `MAILGUN_ESPBLOCK_550`) | final status `blocked`, shown as **Failed** with `SENDGRID_BLOCKED_x00`; `bounced` stays false | `magic-mail.delivery.blocked` | +| SendGrid `dropped` for a sender-side reason (`Invalid SMTPAPI header`, `Invalid Template`, `Template Render Failure`, `Domain is not allowed`, `Expired`, or an unknown reason), Mailgun `failed` + `permanent` with code 621 (template not found, `MAILGUN_TEMPLATE_NOT_FOUND`) | **Failed**, code `SENDGRID_DROPPED_` (unknown reasons: `SENDGRID_DROPPED_OTHER`) | `magic-mail.delivery.dropped` | +| SendGrid `spamreport`, SendGrid `dropped` with reason `Spam Reporting Address`, Mailgun `complained` | `complained: true` (a drop also sets **Failed**) | `magic-mail.delivery.complained` | +| SendGrid `unsubscribe` / `group_unsubscribe`, SendGrid `dropped` with reason `Unsubscribed Address` / `Group Unsubscribe`, Mailgun `unsubscribed` | `unsubscribed: true`, `unsubscribedAt` (a drop also sets **Failed**) | `magic-mail.delivery.unsubscribed` | +| SendGrid `group_resubscribe` | `unsubscribed: false` (only when newer than the unsubscribe) | `magic-mail.delivery.resubscribed` | +| SendGrid `deferred`, Mailgun `failed` + `temporary` (code 621: `MAILGUN_TEMPLATE_NOT_FOUND`) | **Deferred**, code such as `MAILGUN_DEFERRED_421` | `magic-mail.delivery.deferred` | +| SendGrid `delivered`, Mailgun `delivered` | `deliveryConfirmedAt` set; a **Deferred** mail returns to **Sent** | `magic-mail.delivery.delivered` | +| Brevo `hard_bounce` and `invalid_email`, SES `Bounce` with type `Permanent` | **Bounced** (suppressible), code such as `BREVO_HARD_BOUNCE`, `SES_BOUNCE_GENERAL` (SES bounce subtype) | `magic-mail.delivery.bounced` | +| Brevo `soft_bounce` and `deferred`, SES `DeliveryDelay` | **Deferred** | `magic-mail.delivery.deferred` | +| Brevo `blocked`, SES `Bounce` with type `Transient` or `Undetermined` (SES publishes these only after it stopped retrying) | final status `blocked`, not suppressed | `magic-mail.delivery.blocked` | +| Brevo `error`, SES `Reject` and `Rendering Failure` | **Failed** | `magic-mail.delivery.dropped` | +| Brevo `spam`, SES `Complaint` | `complained: true` | `magic-mail.delivery.complained` | +| Brevo `unsubscribed`, SES `Subscription` (unsubscribe) | `unsubscribed: true` | `magic-mail.delivery.unsubscribed` | +| Brevo `delivered`, SES `Delivery` | `deliveryConfirmedAt` set | `magic-mail.delivery.delivered` | Rules: - `deliveredAt` is the time the provider **accepted** the mail (the send call returned). `deliveryConfirmedAt` is the time the receiving server accepted it, known only with the optional `delivered` events. - Bounced, blocked and failed are final: a later deferred, delivered or block never changes them, and a deferred older than the last applied event is recorded but ignored. A hard bounce always wins. - A mail with several recipients has one email log, keyed to the first `to` address. Only events for that address change the log. Events for cc, bcc and further recipients are stored as email events with a masked address (`j***@example.com`) and `primary: false`. -- With **Block hard-bounced recipients** on (Plugin Settings), hard bounces add the address to the [suppression list](#recipient-checks-before-sending) with source `sendgrid` or `mailgun`, so routing and failover to any other account skip it too. Mailgun failures with reason `suppress-*` (Mailgun's own list blocked the send) or `old` are not added. Complaints are added only with the plugin config `webhooks.suppressComplaints: true`; unsubscribes never are, because your app owns consent. +- With **Block hard-bounced recipients** on (Plugin Settings), hard bounces add the address to the [suppression list](#recipient-checks-before-sending) with source `sendgrid` or `mailgun`, so routing and failover to any other account skip it too. Mailgun failures are added only when they are permanent hard bounces: not with severity `temporary`, not with reason `suppress-*` (Mailgun's own list blocked the send), `old` (Mailgun gave up retrying) or `espblock` (the recipient's provider refused the sender, not the address), not when Mailgun marks them `bounce-type: soft`, and not for code 621 (template not found). Complaints are added only with the plugin config `webhooks.suppressComplaints: true`; unsubscribes never are, because your app owns consent. - Events are matched to the email log by the provider message id. SendGrid delayed or asynchronous bounces carry no message id; MagicMail then tries the `magicmail_id` custom argument (the email log id, when the send path sets it) and the `smtp-id`. Events that match no log are counted and logged as a number only, never with addresses. - Only codes are stored, never provider texts or addresses of the primary recipient; the address is already on the email log. diff --git a/docs/live-webhook-checks.md b/docs/live-webhook-checks.md index 5ddeeab..c5386a4 100644 --- a/docs/live-webhook-checks.md +++ b/docs/live-webhook-checks.md @@ -5,9 +5,10 @@ Part of the [MagicMail documentation](https://schero94.github.io/Magic-Mail/). H The unit tests replay the providers' published sample events with locally generated signatures. They cannot prove how your real SendGrid or Mailgun account behaves. This page lists the checks you can run yourself against a -real account. MagicMail's maintainers have not run them; every step marked -**unverified** is not covered by the providers' official documentation, so -write down what you observe. +real account. Every step marked **unverified** is not covered by the +providers' official documentation, so write down what you observe. The +maintainers' own Mailgun run (US sandbox domain, 2026-11-19) is recorded in +[Mailgun live acceptance](./acceptance/2026-11-19-mailgun-live.md). ## Before you start @@ -84,8 +85,9 @@ Neither SendGrid sandbox mode nor the providers' test buttons create real delivery events (SendGrid: sandbox requests "will not generate events in either Event Webhook or Email Activity", ). -**Unverified:** whether Mailgun test mode (`o:testmode`) emits webhooks; the -official docs do not say. So this check sends real mail. +Mailgun test mode (`o:testmode`) does emit `delivered` webhooks (code 650, +`is-test-mode: true`; observed 2026-11-19, the official docs do not say), but +no failures, so this check sends real mail. Setup: diff --git a/docs/sending.md b/docs/sending.md index 869a1c4..b37c5bc 100644 --- a/docs/sending.md +++ b/docs/sending.md @@ -485,7 +485,7 @@ The `data` object is the one a local template gets: MagicMail sends it as SendGr | Which accounts send | Only accounts where the sync found the template. Routing rules, the primary account and failover work as usual among those accounts. An explicit `accountName` without the template is an error. | | Subject | The template's subject. SendGrid always uses the template subject (use `{{subject}}` in it and pass `subject` in `data` for a per-mail subject). Mailgun uses `subject` when you pass one and the template's Subject header otherwise; a Mailgun template without a Subject header needs `subject`. | | Sender | The MagicMail account's verified From, as for every other mail. | -| Missing or unpublished template | A clear error naming the template (`MAGIC_MAIL_PROVIDER_TEMPLATE_UNAVAILABLE`, `MAGIC_MAIL_PROVIDER_TEMPLATE_UNKNOWN`). No other body is sent. | +| Missing or unpublished template | A clear error naming the template (`MAGIC_MAIL_PROVIDER_TEMPLATE_UNAVAILABLE`, `MAGIC_MAIL_PROVIDER_TEMPLATE_UNKNOWN`). No other body is sent. Mailgun accepts a send with a template it does not have and drops the mail later, so before a Mailgun template send MagicMail checks that the template still exists with an active version (cached for 60 seconds after a successful check; if the check itself fails, the send goes ahead). | | Fallback | Optional, per template: **Fallback template** in the dialog sends a local MagicMail template with the same `data` instead, but only when no provider accepted the message (missing template, provider refusal, no account available). An ambiguous error (for example a timeout after sending) never triggers it. | | Size limits | Mailgun accepts 16 KB for all send options (`t:variables` plus headers); SendGrid accepts messages under 30 MB. MagicMail also bounds template data to 1 MB. Larger mails fail before anything is sent with `MAGIC_MAIL_PROVIDER_TEMPLATE_TOO_LARGE`. For Mailgun the 16 KB also include the `v:magicmail_*` variables and `o:tag` that MagicMail adds to every send. | | Tracking | The provider renders the body, so MagicMail adds no open pixel or link tracking. With **Count provider opens and clicks** (Plugin Settings, off by default) MagicMail asks SendGrid, Mailgun and SES to track the template mail and counts their open and click webhook events in Email Analytics; Brevo tracks at account level and its `opened`/`click` events are counted the same way. See [provider opens and clicks](./delivery.md#provider-opens-and-clicks). | diff --git a/server/src/services/delivery-webhooks.js b/server/src/services/delivery-webhooks.js index afc9db0..6ba5fb1 100644 --- a/server/src/services/delivery-webhooks.js +++ b/server/src/services/delivery-webhooks.js @@ -22,8 +22,9 @@ const { getAdapter, WEBHOOK_PROVIDERS } = require('../providers'); * provider's next retry is processed. The in-memory map is a first-level * cache in front of the table. * - Outcomes (see README "Bounces and complaints"): - * bounced (hard bounce), blocked (SendGrid block, final), dropped (SendGrid - * drop for a sender-side reason, final), deferred, delivered, complained, + * bounced (hard bounce), blocked (SendGrid block or Mailgun `espblock`, + * final), dropped (SendGrid drop for a sender-side reason, or a Mailgun + * template that no longer exists, final), deferred, delivered, complained, * unsubscribed, resubscribed. Each is stored on the email log (primary * recipient only) plus one email event, and emitted on `strapi.eventHub` as * `magic-mail.delivery.` with @@ -45,6 +46,9 @@ const EMAIL_EVENT_UID = 'plugin::magic-mail.email-event'; const PROVIDERS = new Set(WEBHOOK_PROVIDERS); const ACCOUNT_ID_PATTERN = /^[A-Za-z0-9]{1,64}$/; +/** Mailgun delivery-status code for "Template not found" (Mailgun-internal, not SMTP). */ +const MAILGUN_TEMPLATE_NOT_FOUND_CODE = 621; + /** Log documentId sent as SendGrid custom_args / Mailgun v: variable `magicmail_id`. */ const MAGICMAIL_ID_PATTERN = /^[A-Za-z0-9]{1,64}$/; const EVENT_ID_PATTERN = /^[\x21-\x7e]{1,128}$/; @@ -340,11 +344,22 @@ function parseSendGridEvents(payload) { * Maps one Mailgun webhook (`event-data`) to a delivery event. * * Sources: https://documentation.mailgun.com/docs/mailgun/user-manual/webhooks/webhooks - * (event types) and the Mailgun API bundle `EventSeverityType` (temporary = - * Mailgun retries, permanent = no retry). + * (event types), the Mailgun API bundle `EventSeverityType` (temporary = + * Mailgun retries, permanent = no retry) and the Mailgun OpenAPI metrics + * (`hard_bounces` / `soft_bounces` by `delivery-status.bounce-type`, + * `esp_block` by reason `espblock`). * - failed + permanent -> bounced; suppressible unless the reason is - * `suppress-*` (Mailgun's own list already blocked it) or `old`. - * - failed + temporary -> deferred. + * `suppress-*` (Mailgun's own list already blocked it) or `old`, or + * Mailgun classified it as a soft bounce (`bounce-type: soft`). + * - failed + permanent + reason `espblock` -> blocked, never suppressed: the + * recipient's provider refused the sender (reputation, authentication), + * not the address. Seen live 2026-11-19: 550 5.7.40 with `bounce-type: + * soft`; Mailgun did not add the address to its own bounce list. + * - failed + delivery-status code 621 ("Template not found", a Mailgun code, + * not SMTP; seen live 2026-11-19 as severity temporary, retried every + * 600 s) -> deferred while temporary, dropped (failed) when permanent; + * reason code MAILGUN_TEMPLATE_NOT_FOUND, never suppressed. + * - failed + temporary -> deferred, never suppressed. * - complained, unsubscribed, delivered. * - opened, clicked (counted only for provider-tracked logs). * @@ -368,10 +383,24 @@ function parseMailgunEvent(eventData) { suppress: null, notDelivered: false, }; - const smtp = eventData['delivery-status'] && eventData['delivery-status'].code; + const status = + eventData['delivery-status'] && typeof eventData['delivery-status'] === 'object' + ? eventData['delivery-status'] + : {}; + const smtp = status.code; + const templateMissing = Number(smtp) === MAILGUN_TEMPLATE_NOT_FOUND_CODE; if (eventData.event === 'failed' && eventData.severity === 'permanent') { const reason = typeof eventData.reason === 'string' ? eventData.reason : ''; - const suppressible = !reason.startsWith('suppress-') && reason !== 'old'; + if (templateMissing) { + return [ + { ...base, kind: 'dropped', reasonCode: reasonCode('mailgun', 'template-not-found') }, + ]; + } + if (reason === 'espblock') { + return [{ ...base, kind: 'blocked', reasonCode: reasonCode('mailgun', reason, smtp) }]; + } + const suppressible = + !reason.startsWith('suppress-') && reason !== 'old' && status['bounce-type'] !== 'soft'; return [ { ...base, @@ -382,7 +411,15 @@ function parseMailgunEvent(eventData) { ]; } if (eventData.event === 'failed' && eventData.severity === 'temporary') { - return [{ ...base, kind: 'deferred', reasonCode: reasonCode('mailgun', 'deferred', smtp) }]; + return [ + { + ...base, + kind: 'deferred', + reasonCode: templateMissing + ? reasonCode('mailgun', 'template-not-found') + : reasonCode('mailgun', 'deferred', smtp), + }, + ]; } if (eventData.event === 'complained') { return [ diff --git a/server/src/services/email-router.js b/server/src/services/email-router.js index 906b7ae..2f82ee6 100644 --- a/server/src/services/email-router.js +++ b/server/src/services/email-router.js @@ -13,6 +13,7 @@ const { checkRecipientDomains } = require('../utils/recipient-domains'); const { toPlainJson } = require('../utils/plain-json'); const { canonicalLocale } = require('../utils/locale'); const { getAdapter, TEMPLATE_PROVIDERS } = require('../providers'); +const { checkMailgunTemplate } = require('../utils/provider-api'); const { classifyDeliveryError, combineOutcome, @@ -53,6 +54,19 @@ const MAX_ROUTING_CANDIDATES = 25; const SENDGRID_MAX_MESSAGE_BYTES = 30_000_000; const MAILGUN_MAX_MESSAGE_BYTES = 25_000_000; const MAILGUN_MAX_OPTIONS_BYTES = 16 * 1024; + +/** + * Pre-send Mailgun template check cache: positive results only, per + * account + region + domain + scope + template name, for 60 s, so a bulk + * send makes one extra request per template and minute, not one per mail. + * Per process; a template deleted at Mailgun is noticed within the TTL. + */ +const MAILGUN_TEMPLATE_CHECK_TTL_MS = 60_000; +const MAILGUN_TEMPLATE_CHECK_MAX_ENTRIES = 1000; +/** @type {Map} cache key -> expiry (ms since epoch) */ +const mailgunTemplateChecks = new Map(); +/** @type {Map>} checks in flight, shared by parallel sends */ +const mailgunTemplateChecksInFlight = new Map(); /** Raw (decoded) size of all attachments of one message, for every provider. */ const MAX_TOTAL_ATTACHMENT_BYTES = 40 * 1024 * 1024; /** A provider error body is read up to this size, parsed, then discarded. */ @@ -3319,7 +3333,10 @@ module.exports = ({ strapi }) => ({ * @throws {Error} Account configuration error (key, domain, region) * @throws {errors.ValidationError} Invalid message, or MAGIC_MAIL_MESSAGE_TOO_LARGE * @throws {Error} "Mailgun API request failed: " with `status` and `provider` - * @sideeffect One HTTPS request to Mailgun with the recipients and content. + * @throws {Error} ProviderTemplateError MAGIC_MAIL_PROVIDER_TEMPLATE_UNAVAILABLE when a + * template send names a template that is gone at Mailgun (see ensureMailgunTemplateAvailable) + * @sideeffect One HTTPS request to Mailgun with the recipients and content; for a + * template send, first a cached template check (GET, at most once a minute). */ async sendViaMailgun(account, emailData) { const config = readAccountSecret(account.config); @@ -3348,6 +3365,10 @@ module.exports = ({ strapi }) => ({ this.validateEmailSecurity(emailData); + if (template) { + await this.ensureMailgunTemplateAvailable(account, { ...config, domain }, region, template); + } + try { const form = new FormData(); const joinAddrs = (value) => (Array.isArray(value) ? value.join(', ') : value); @@ -3459,6 +3480,80 @@ module.exports = ({ strapi }) => ({ } }, + /** + * Refuses a Mailgun template send when the template was deleted at Mailgun + * (or lost its active version) after Magic Mail synced it. Mailgun accepts + * such a send with 200 "Queued" and drops the message later (event + * `failed`, delivery-status 621 "Template not found"), so without this + * check the mail would be logged as sent and be lost. + * + * Positive results are cached for 60 s per account and template. A 404 or a + * template without an active version throws MAGIC_MAIL_PROVIDER_TEMPLATE_UNAVAILABLE + * before any message request: marked pre-dispatch (the next account that + * has the template may send) and fallback-safe (the configured Magic Mail + * fallback template applies). Any other outcome of the check (network, + * timeout, 401/403, 429, 5xx, unreadable body) does not block the send: it + * logs a warning and the send goes ahead. + * + * @param {object} account - Mailgun account (documentId keys the cache) + * @param {{apiKey: string, domain: string}} config - Decrypted config, normalised domain + * @param {'us'|'eu'} region + * @param {{name: string, scope: string}} template - Result of providerTemplateFor() + * @returns {Promise} + * @throws {Error} ProviderTemplateError MAGIC_MAIL_PROVIDER_TEMPLATE_UNAVAILABLE + * @sideeffect At most one HTTPS GET to Mailgun per account, template and minute. + */ + async ensureMailgunTemplateAvailable(account, config, region, template) { + const scope = template.scope === 'account' ? 'account' : 'domain'; + const cacheKey = [ + account.documentId || account.id || '', + region, + config.domain, + scope, + template.name, + ].join('\u0000'); + const now = Date.now(); + const expiresAt = mailgunTemplateChecks.get(cacheKey); + if (expiresAt && expiresAt > now) return; + if (expiresAt) mailgunTemplateChecks.delete(cacheKey); + + let pending = mailgunTemplateChecksInFlight.get(cacheKey); + if (!pending) { + pending = checkMailgunTemplate(config, region, { name: template.name, scope }); + mailgunTemplateChecksInFlight.set(cacheKey, pending); + pending.finally(() => mailgunTemplateChecksInFlight.delete(cacheKey)).catch(() => {}); + } + + let state; + try { + state = await pending; + } catch (error) { + strapi.log.warn( + `[magic-mail] Mailgun template check failed (${error?.code || error?.name || 'Error'}); sending without it` + ); + return; + } + + if (state === 'available') { + if (mailgunTemplateChecks.size >= MAILGUN_TEMPLATE_CHECK_MAX_ENTRIES) { + // Map keeps insertion order: drop the oldest entry. + mailgunTemplateChecks.delete(mailgunTemplateChecks.keys().next().value); + } + mailgunTemplateChecks.set(cacheKey, Date.now() + MAILGUN_TEMPLATE_CHECK_TTL_MS); + return; + } + + strapi.log.warn( + `[magic-mail] Mailgun template is ${state === 'missing' ? 'deleted' : 'without an active version'} at the provider; message not sent` + ); + throw tagPreDispatch( + providerTemplateError( + `The Mailgun template "${template.name}" is deleted or has no active version at Mailgun. Sync the provider templates in Magic Mail`, + 'MAGIC_MAIL_PROVIDER_TEMPLATE_UNAVAILABLE' + ) + ); + }, + /** @returns {string} Configured quota time zone (default UTC) */ getQuotaTimeZone() { try { @@ -3765,6 +3860,12 @@ module.exports = ({ strapi }) => ({ module.exports.__test__ = { HTML_SANITIZE_OPTIONS, + MAILGUN_TEMPLATE_CHECK_TTL_MS, + /** Empties the pre-send Mailgun template check cache (tests only). */ + resetMailgunTemplateChecks: () => { + mailgunTemplateChecks.clear(); + mailgunTemplateChecksInFlight.clear(); + }, providerSendHelpers, MAILGUN_MAX_MESSAGE_BYTES, MAILGUN_MAX_OPTIONS_BYTES, diff --git a/server/src/utils/provider-api.js b/server/src/utils/provider-api.js index 5f8c8cf..f957da0 100644 --- a/server/src/utils/provider-api.js +++ b/server/src/utils/provider-api.js @@ -99,17 +99,18 @@ async function readBounded(response, maxBytes) { * * @param {string} url - Absolute URL on a fixed provider host * @param {Record} headers - Authorization header + * @param {{timeoutMs?: number}} [options] - Request timeout (default 15 s) * @returns {Promise} Parsed JSON * @throws {ProviderApiError} */ -async function getJson(url, headers) { +async function getJson(url, headers, { timeoutMs = REQUEST_TIMEOUT_MS } = {}) { let response; try { response = await fetch(url, { method: 'GET', headers: { Accept: 'application/json', ...headers }, redirect: 'error', - signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS), + signal: AbortSignal.timeout(timeoutMs), }); } catch { throw new ProviderApiError('NETWORK'); @@ -344,10 +345,70 @@ async function listMailgunTemplates(config, region, { pageSize = MAILGUN_PAGE_LI return { templates, accountScopeError }; } +/** Timeout of the pre-send template check: short, a slow check must not stall sends. */ +const MAILGUN_TEMPLATE_CHECK_TIMEOUT_MS = 5_000; + +/** + * Checks that a Mailgun template still exists and has an active version, + * right before a template send. Mailgun accepts a send with an unknown + * template name (200 "Queued") and drops the message later (event `failed`, + * delivery-status code 621 "Template not found"), so the send path asks + * first. + * + * Domain templates: GET /v3/{domain}/templates/{name}?active=yes. + * Account templates: GET /v4/templates/{name}?active=yes (the account-level + * get takes the template name, like the domain one). Both answer 404 + * `{"message":"template not found"}` for a missing template, and 200 without + * `template.version` for a template that has no version (verified against the + * US API on 2026-11-19). + * + * @param {{apiKey: string, domain: string}} config - Decrypted account config + * @param {'us'|'eu'} region - Resolved Mailgun region + * @param {{name: string, scope?: string}} template - Template name and scope ('account' or domain) + * @param {{timeoutMs?: number}} [options] + * @returns {Promise<'available'|'missing'|'no-active-version'>} + * @throws {ProviderApiError} For every other outcome (auth, rate limit, 5xx, + * network, unreadable body); callers decide whether that blocks a send + * @sideeffect One HTTPS GET to the Mailgun API of the region. + */ +async function checkMailgunTemplate( + config, + region, + template, + { timeoutMs = MAILGUN_TEMPLATE_CHECK_TIMEOUT_MS } = {} +) { + const base = mailgunApiBaseUrl(region); + const domain = String(config.domain).trim().toLowerCase(); + const path = + template.scope === 'account' + ? `/v4/templates/${encodeURIComponent(template.name)}` + : `/v3/${encodeURIComponent(domain)}/templates/${encodeURIComponent(template.name)}`; + const url = new URL(path, base); + url.searchParams.set('active', 'yes'); + let body; + try { + body = await getJson( + url.toString(), + { Authorization: `Basic ${Buffer.from(`api:${config.apiKey}`).toString('base64')}` }, + { timeoutMs } + ); + } catch (error) { + if (error instanceof ProviderApiError && error.code === 'NOT_FOUND') return 'missing'; + throw error; + } + const found = body?.template; + if (!found || typeof found !== 'object') throw new ProviderApiError('BAD_RESPONSE'); + const version = found.version && typeof found.version === 'object' ? found.version : null; + if (!version || version.active === false) return 'no-active-version'; + return 'available'; +} + module.exports = { + MAILGUN_TEMPLATE_CHECK_TIMEOUT_MS, MAX_RESPONSE_BYTES, ProviderApiError, SENDGRID_REGIONS, + checkMailgunTemplate, codeForStatus, listMailgunTemplates, listSendGridTemplates, diff --git a/tests/live/provider-templates.live.test.js b/tests/live/provider-templates.live.test.js index c2e4c26..2deb4dd 100644 --- a/tests/live/provider-templates.live.test.js +++ b/tests/live/provider-templates.live.test.js @@ -250,7 +250,7 @@ liveSendGrid('an unknown SendGrid template key fails in the plugin', async () => }); liveMailgun( - 'an unknown Mailgun key fails in the plugin; an unknown id is refused by the provider', + 'an unknown Mailgun key fails in the plugin; a template deleted at Mailgun is refused before sending', async () => { await assert.rejects( harness() @@ -268,12 +268,25 @@ liveMailgun( remoteScope: 'domain', }; rows.push(ghost); + // Mailgun itself answers 200 "Queued" for an unknown template name and + // drops the message later (event `failed`, delivery-status 621 "Template + // not found"; checked 2026-11-19). Magic Mail must ask Mailgun first + // (GET /v3/{domain}/templates/{name}?active=yes -> 404) and send nothing. + const before = live.sent.mailgun.length; await assert.rejects( harness() .service('email-router') .send({ to: env.LIVE_TEST_RECIPIENT, providerTemplate: 'mailgun:ghost', subject: 'x' }), - (error) => Number(error.status) >= 400 && Number(error.status) < 500 + (error) => error.code === 'MAGIC_MAIL_PROVIDER_TEMPLATE_UNAVAILABLE' + ); + assert.equal(live.sent.mailgun.length, before, 'no message request reached Mailgun'); + // The request log masks the domain and the (long) template name. + const check = live.results.at(-1); + assert.ok( + check?.method === 'GET' && check.path.startsWith('/v3//templates/'), + 'the last request was the template check' ); + assert.equal(check.status, 404, 'Mailgun reports the deleted template as 404'); } ); diff --git a/tests/mailgun-template-check.test.js b/tests/mailgun-template-check.test.js new file mode 100644 index 0000000..1deddec --- /dev/null +++ b/tests/mailgun-template-check.test.js @@ -0,0 +1,408 @@ +'use strict'; + +// Pre-send Mailgun template check (sendViaMailgun, template branch). +// +// Mailgun accepts a send with a template name that does not exist (200 +// "Queued") and drops the message later (event `failed`, delivery-status 621 +// "Template not found"; verified live 2026-11-19). Magic Mail therefore asks +// GET /v3/{domain}/templates/{name}?active=yes (domain scope) or +// GET /v4/templates/{name}?active=yes (account scope) before a template send. +// +// Against the fake Mailgun server; synthetic data only, no request leaves +// 127.0.0.1. + +const test = require('node:test'); +const assert = require('node:assert/strict'); +const { + createState, + redirectProviderFetch, + startFakeProviders, +} = require('./helpers/fake-template-providers'); +const { createStrapi } = require('./helpers/provider-template-strapi'); +const { encryptCredentials } = require('../server/src/utils/encryption'); +const { checkMailgunTemplate, ProviderApiError } = require('../server/src/utils/provider-api'); +const ROUTER_PATH = '../server/src/services/email-router'; +const { MAILGUN_TEMPLATE_CHECK_TTL_MS } = require(ROUTER_PATH).__test__; + +/** + * Empties the check cache of the email-router module the newest harness + * loaded (the harness re-requires each service, so every harness has its own + * module instance and cache). + */ +const resetMailgunTemplateChecks = () => require(ROUTER_PATH).__test__.resetMailgunTemplateChecks(); + +let fake; +let state; +let restoreFetch; +let previousKey; + +test.before(async () => { + previousKey = process.env.MAGIC_MAIL_ENCRYPTION_KEY; + process.env.MAGIC_MAIL_ENCRYPTION_KEY = 'q'.repeat(32); + state = createState(); + fake = await startFakeProviders(state); + restoreFetch = redirectProviderFetch(fake.port); +}); + +test.after(async () => { + restoreFetch(); + await fake.close(); + if (previousKey === undefined) delete process.env.MAGIC_MAIL_ENCRYPTION_KEY; + else process.env.MAGIC_MAIL_ENCRYPTION_KEY = previousKey; +}); + +/** Fresh fake provider data and an empty check cache. */ +function reset() { + const fresh = createState(); + for (const key of Object.keys(fresh)) state[key] = fresh[key]; + resetMailgunTemplateChecks(); +} + +/** Collecting logger: messages only. */ +function recordingLog() { + const lines = { warn: [], error: [] }; + return { + lines, + log: { + debug() {}, + info() {}, + warn: (message) => lines.warn.push(String(message)), + error: (message) => lines.error.push(String(message)), + }, + }; +} + +function mailgunAccount( + documentId, + { domain = 'mg.example.test', region = 'us', priority = 4 } = {} +) { + return { + documentId, + name: documentId, + provider: 'mailgun', + fromEmail: `noreply@${domain}`, + isActive: true, + priority, + config: encryptCredentials({ apiKey: `key-${documentId}`, domain, region }), + }; +} + +function mgTemplate(name, { active = true } = {}) { + return { + name, + id: `mg-${name}`, + createdAt: 'Mon, 10 Nov 2026 08:30:00 UTC', + version: active + ? { + tag: 'v1', + template: '

Hi {{name}}

', + engine: 'handlebars', + createdAt: 'Tue, 11 Nov 2026 09:00:00 UTC', + active: true, + id: `mg-${name}-v1`, + headers: { Subject: 'Welcome {{name}}' }, + } + : null, + }; +} + +const messages = (host = 'api.mailgun.net') => + state.requests.filter( + (r) => r.host === host && r.method === 'POST' && /\/messages$/.test(r.path) + ); +const checks = (host = 'api.mailgun.net') => + state.requests.filter( + (r) => r.host === host && r.method === 'GET' && /\/templates\/[^/]+$/.test(r.path) + ); + +/** Harness with the given accounts, synced once. */ +async function synced(accounts, options = {}) { + const h = createStrapi({ accounts, ...options }); + await h.service('provider-templates').sync({ force: true }); + resetMailgunTemplateChecks(); + state.requests.length = 0; + return h; +} + +test('checkMailgunTemplate: available, missing, no active version; other statuses throw', async () => { + reset(); + state.mailgun.us.domains['mg.example.test'] = [ + mgTemplate('welcome'), + mgTemplate('draft', { active: false }), + ]; + state.mailgun.us.account = [mgTemplate('shared')]; + const config = { apiKey: 'key-x', domain: 'mg.example.test' }; + + assert.equal( + await checkMailgunTemplate(config, 'us', { name: 'welcome', scope: 'domain' }), + 'available' + ); + assert.equal( + await checkMailgunTemplate(config, 'us', { name: 'gone', scope: 'domain' }), + 'missing' + ); + assert.equal( + await checkMailgunTemplate(config, 'us', { name: 'draft', scope: 'domain' }), + 'no-active-version' + ); + assert.equal( + await checkMailgunTemplate(config, 'us', { name: 'shared', scope: 'account' }), + 'available' + ); + assert.equal( + await checkMailgunTemplate(config, 'us', { name: 'welcome', scope: 'account' }), + 'missing' + ); + + const paths = checks().map((r) => `${r.path}?active=${r.query.active}`); + assert.deepEqual(paths, [ + '/v3/mg.example.test/templates/welcome?active=yes', + '/v3/mg.example.test/templates/gone?active=yes', + '/v3/mg.example.test/templates/draft?active=yes', + '/v4/templates/shared?active=yes', + '/v4/templates/welcome?active=yes', + ]); + assert.ok(checks().every((r) => r.authorization === 'present')); + + for (const status of [401, 429, 500, 503]) { + state.failures.push({ + host: 'api.mailgun.net', + method: 'GET', + pathPrefix: '/v3/mg.example.test/templates/', + status, + times: 1, + }); + await assert.rejects( + checkMailgunTemplate(config, 'us', { name: 'welcome', scope: 'domain' }), + (error) => error instanceof ProviderApiError && error.status === status + ); + } +}); + +test('a template deleted at Mailgun after the sync is refused before any message request', async () => { + reset(); + state.mailgun.us.domains['mg.example.test'] = [mgTemplate('welcome')]; + const { lines, log } = recordingLog(); + const h = await synced([mailgunAccount('mg1')], { log }); + state.mailgun.us.domains['mg.example.test'] = []; // deleted in the Mailgun dashboard + + await assert.rejects( + h.service('email-router').send({ to: 'a@example.test', providerTemplate: 'mailgun:welcome' }), + (error) => + error.code === 'MAGIC_MAIL_PROVIDER_TEMPLATE_UNAVAILABLE' && + error.name === 'ProviderTemplateError' && + !/example\.test/.test(error.message) + ); + assert.equal(messages().length, 0, 'no message request was sent'); + assert.equal(checks().length, 1); + assert.equal( + h.logUpdates.at(-1)?.fields?.deliveryStatus, + 'failed', + 'the log row is failed, not sent' + ); + assert.ok(lines.warn.concat(lines.error).every((line) => !/example\.test|key-/.test(line))); +}); + +test('a template without an active version is refused the same way', async () => { + reset(); + state.mailgun.us.domains['mg.example.test'] = [mgTemplate('welcome')]; + const h = await synced([mailgunAccount('mg1')]); + state.mailgun.us.domains['mg.example.test'] = [mgTemplate('welcome', { active: false })]; + await assert.rejects( + h.service('email-router').send({ to: 'a@example.test', providerTemplate: 'mailgun:welcome' }), + (error) => error.code === 'MAGIC_MAIL_PROVIDER_TEMPLATE_UNAVAILABLE' + ); + assert.equal(messages().length, 0); +}); + +test('positive results are cached for 60 s per account and template; negatives are not', async (t) => { + reset(); + state.mailgun.us.domains['mg.example.test'] = [mgTemplate('welcome')]; + const h = await synced([mailgunAccount('mg1')]); + const send = () => + h.service('email-router').send({ to: 'a@example.test', providerTemplate: 'mailgun:welcome' }); + + await send(); + await send(); + await Promise.all([send(), send(), send()]); + assert.equal(messages().length, 5); + assert.equal(checks().length, 1, 'one template check for five sends'); + + // After the TTL the template is checked again. + const realNow = Date.now; + t.after(() => { + Date.now = realNow; + }); + const later = realNow() + MAILGUN_TEMPLATE_CHECK_TTL_MS + 1; + Date.now = () => later; + await send(); + assert.equal(checks().length, 2, 'checked again after 60 s'); + Date.now = realNow; + + // A negative result is not cached: once the template is back, sends work. + resetMailgunTemplateChecks(); + state.mailgun.us.domains['mg.example.test'] = []; + await assert.rejects( + send(), + (error) => error.code === 'MAGIC_MAIL_PROVIDER_TEMPLATE_UNAVAILABLE' + ); + state.mailgun.us.domains['mg.example.test'] = [mgTemplate('welcome')]; + await send(); + assert.equal(messages().length, 7); +}); + +test('parallel sends share one check in flight', async () => { + reset(); + state.mailgun.us.domains['mg.example.test'] = [mgTemplate('welcome')]; + const h = await synced([mailgunAccount('mg1')]); + await Promise.all( + Array.from({ length: 10 }, () => + h.service('email-router').send({ to: 'a@example.test', providerTemplate: 'mailgun:welcome' }) + ) + ); + assert.equal(messages().length, 10); + assert.equal(checks().length, 1); +}); + +test('account-level templates are checked with GET /v4/templates/{name}?active=yes', async () => { + reset(); + state.mailgun.us.account = [mgTemplate('shared')]; + const h = await synced([mailgunAccount('mg1')]); + await h + .service('email-router') + .send({ to: 'a@example.test', providerTemplate: 'mailgun:shared' }); + assert.deepEqual( + checks().map((r) => [r.path, r.query.active]), + [['/v4/templates/shared', 'yes']] + ); + state.mailgun.us.account = []; + resetMailgunTemplateChecks(); + await assert.rejects( + h.service('email-router').send({ to: 'a@example.test', providerTemplate: 'mailgun:shared' }), + (error) => error.code === 'MAGIC_MAIL_PROVIDER_TEMPLATE_UNAVAILABLE' + ); + assert.equal(messages().length, 1); +}); + +test('EU accounts check on api.eu.mailgun.net', async () => { + reset(); + state.mailgun.eu.domains['mg.example.test'] = [mgTemplate('welcome')]; + const h = await synced([mailgunAccount('mg1', { region: 'eu' })]); + await h + .service('email-router') + .send({ to: 'a@example.test', providerTemplate: 'mailgun:welcome' }); + assert.equal(checks('api.eu.mailgun.net').length, 1); + assert.equal(checks('api.mailgun.net').length, 0); +}); + +test('network, timeout-like, auth, 429 and 5xx failures of the check do not block the send', async () => { + reset(); + state.mailgun.us.domains['mg.example.test'] = [mgTemplate('welcome')]; + const { lines, log } = recordingLog(); + const h = await synced([mailgunAccount('mg1')], { log }); + for (const status of [500, 503, 429, 401]) { + resetMailgunTemplateChecks(); + state.failures.push({ + host: 'api.mailgun.net', + method: 'GET', + pathPrefix: '/v3/mg.example.test/templates/', + status, + times: 1, + }); + const result = await h + .service('email-router') + .send({ to: 'a@example.test', providerTemplate: 'mailgun:welcome' }); + assert.equal(result.success, true, `send goes ahead after a ${status} check`); + } + assert.equal(messages().length, 4); + const warnings = lines.warn.filter((line) => line.includes('Mailgun template check failed')); + assert.equal(warnings.length, 4); + assert.ok(warnings.every((line) => !/example\.test|key-/.test(line))); + + // A failed check is not cached as positive: the next send checks again. + const before = checks().length; + await h + .service('email-router') + .send({ to: 'a@example.test', providerTemplate: 'mailgun:welcome' }); + assert.equal(checks().length, before + 1); + + // Network error (connection refused) on the check only. + resetMailgunTemplateChecks(); + const previousFetch = global.fetch; + global.fetch = (input, init) => { + const url = new URL(typeof input === 'string' ? input : input.url); + if ((init?.method || 'GET') === 'GET' && url.pathname.includes('/templates/')) { + const error = new TypeError('fetch failed'); + error.cause = Object.assign(new Error('connect ECONNREFUSED'), { code: 'ECONNREFUSED' }); + return Promise.reject(error); + } + return previousFetch(input, init); + }; + try { + const result = await h + .service('email-router') + .send({ to: 'a@example.test', providerTemplate: 'mailgun:welcome' }); + assert.equal(result.success, true); + } finally { + global.fetch = previousFetch; + } + assert.ok(lines.warn.some((line) => line.includes('check failed (NETWORK)'))); +}); + +test('a deleted template uses the configured Magic Mail fallback template', async () => { + reset(); + state.mailgun.us.domains['mg.example.test'] = [mgTemplate('welcome')]; + const local = { + documentId: 'tpl1', + templateReferenceId: 77, + name: 'Local welcome', + subject: 'Local {{name}}', + bodyHtml: '

Local {{name}}

', + bodyText: '', + category: 'transactional', + isActive: true, + }; + const h = await synced([mailgunAccount('mg1')], { localTemplates: [local] }); + await h.service('provider-templates').setFallback('mailgun:welcome', 77); + state.mailgun.us.domains['mg.example.test'] = []; + + const result = await h.service('email-router').send({ + to: 'a@example.test', + providerTemplate: 'mailgun:welcome', + data: { name: 'Ada' }, + }); + assert.equal(result.fallback, 'magic-mail-template'); + const sent = messages(); + assert.equal(sent.length, 1, 'only the fallback mail was sent'); + const form = Object.fromEntries(sent[0].form); + assert.equal(form.template, undefined); + assert.equal(form.subject, 'Local Ada'); +}); + +test('another account that still has the template takes over (nothing was sent)', async () => { + reset(); + state.mailgun.us.domains['a.example.test'] = [mgTemplate('welcome')]; + state.mailgun.us.domains['b.example.test'] = [mgTemplate('welcome')]; + const h = await synced([ + mailgunAccount('mgA', { domain: 'a.example.test', priority: 9 }), + mailgunAccount('mgB', { domain: 'b.example.test', priority: 8 }), + ]); + state.mailgun.us.domains['a.example.test'] = []; + const result = await h + .service('email-router') + .send({ to: 'a@example.test', providerTemplate: 'mailgun:welcome' }); + assert.equal(result.accountUsed, 'mgB'); + const sent = messages(); + assert.equal(sent.length, 1); + assert.equal(sent[0].path, '/v3/b.example.test/messages'); +}); + +test('normal (non-template) Mailgun sends make no template check', async () => { + reset(); + const h = await synced([mailgunAccount('mg1')]); + await h + .service('email-router') + .send({ to: 'a@example.test', subject: 'Hi', html: '

Hi

', text: 'Hi' }); + assert.equal(messages().length, 1); + assert.equal(checks().length, 0); +}); diff --git a/tests/webhook-outcomes.test.js b/tests/webhook-outcomes.test.js index cbb5be8..019fbce 100644 --- a/tests/webhook-outcomes.test.js +++ b/tests/webhook-outcomes.test.js @@ -715,6 +715,87 @@ test('Mailgun failed permanent: Bounced; suppress-* and old reasons are not supp }); }); +// Shapes observed live against a Mailgun US sandbox domain on 2026-11-19 +// (events API and signed webhook posts; addresses and ids replaced). +test('Mailgun severity and bounce type: only permanent hard bounces suppress', async () => { + await withKey(async ({ encryptCredentials }) => { + const cases = [ + { + label: 'temporary 621 template not found', + severity: 'temporary', + reason: 'generic', + status: { code: 621, 'retry-seconds': 600, 'enhanced-code': '' }, + expect: { status: 'deferred', reasonCode: 'MAILGUN_TEMPLATE_NOT_FOUND', topic: 'deferred' }, + }, + { + label: 'temporary 421 mailbox busy', + severity: 'temporary', + reason: 'generic', + status: { code: 421, 'bounce-type': 'soft' }, + expect: { status: 'deferred', reasonCode: 'MAILGUN_DEFERRED_421', topic: 'deferred' }, + }, + { + label: 'permanent espblock (550 5.7.40, soft)', + severity: 'permanent', + reason: 'espblock', + status: { code: 550, 'enhanced-code': '5.7.40', 'bounce-type': 'soft' }, + expect: { status: 'blocked', reasonCode: 'MAILGUN_ESPBLOCK_550', topic: 'blocked' }, + }, + { + label: 'permanent soft bounce', + severity: 'permanent', + reason: 'bounce', + status: { code: 552, 'bounce-type': 'soft' }, + expect: { status: 'bounced', reasonCode: 'MAILGUN_BOUNCE_552', topic: 'bounced' }, + }, + { + label: 'permanent 621 template not found', + severity: 'permanent', + reason: 'generic', + status: { code: 621 }, + expect: { status: 'failed', reasonCode: 'MAILGUN_TEMPLATE_NOT_FOUND', topic: 'dropped' }, + }, + { + label: 'permanent hard bounce', + severity: 'permanent', + reason: 'bounce', + status: { code: 550, 'enhanced-code': '5.1.1', 'bounce-type': 'hard' }, + expect: { status: 'bounced', reasonCode: 'MAILGUN_BOUNCE_550', topic: 'bounced' }, + suppressed: true, + }, + ]; + for (const item of cases) { + deliveryService.__test__.resetSeen(); + const event = clone(MAILGUN.failedPermanent); + Object.assign(event, { + severity: item.severity, + reason: item.reason, + recipient: 'joan@example.test', + 'delivery-status': { 'attempt-no': 1, message: '', ...item.status }, + }); + const host = createHost({ + provider: 'mailgun', + logs: [ + { + documentId: 'log1', + providerMessageId: event.message.headers['message-id'], + recipient: 'joan@example.test', + }, + ], + settings: { suppressHardBounces: true }, + encryptCredentials, + }); + const result = await sendMailgun(host, event); + assert.equal(result.status, 200, item.label); + assert.equal(host.log().deliveryStatus, item.expect.status, item.label); + assert.equal(host.log().bounceReason, item.expect.reasonCode, item.label); + assert.equal(host.log().bounced === true, item.expect.status === 'bounced', item.label); + assert.deepEqual(topics(host), [`magic-mail.delivery.${item.expect.topic}`], item.label); + assert.equal(host.suppressed().length, item.suppressed ? 1 : 0, item.label); + } + }); +}); + test('Mailgun failed temporary -> deferred; delivered -> confirmation; never downgrades', async () => { await withKey(async ({ encryptCredentials }) => { deliveryService.__test__.resetSeen();