Skip to content
Open
Show file tree
Hide file tree
Changes from 9 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,8 @@ and this project adheres to
`DSFR_THEME_FORGOT_PASSWORD_URL` to the `lst-dsfr` theme
- Add `DSFR_THEME_LAGAUFRE_WIDGET_CONFIG` to show the La Suite services button
in the account console header of the `lst-dsfr` theme
- Route inbound mail to several Messages instances from one pymta, by
recipient domain (`PYMTA_TENANTS_FILE`)

### Changed

Expand Down
4 changes: 4 additions & 0 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -429,6 +429,10 @@ test-mta-in-py-e2e: build-python-base ## run pymta and the real backend together
@bin/test-mta-in-py-e2e
.PHONY: test-mta-in-py-e2e

test-mta-in-py-e2e-tenants: build-python-base ## run one pymta in front of two backends, each with its own database and secret
@bin/test-mta-in-py-e2e-tenants
.PHONY: test-mta-in-py-e2e-tenants

fuzz-mta-in-py: build-python-base ## run the pymta Hypothesis fuzz suite (about a minute; FUZZ_EXAMPLES=n to scale)
@$(COMPOSE) run --build --rm -e EXEC_CMD_ONLY=true -e FUZZ_EXAMPLES mta-in-py-test pytest -q -m fuzz tests/
.PHONY: fuzz-mta-in-py
Expand Down
86 changes: 86 additions & 0 deletions bin/test-mta-in-py-e2e-tenants
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
#!/usr/bin/env bash
# End-to-end test of one pymta in front of two Messages instances: each
# backend on a database of its own, with an MDA secret of its own. Runs in a
# compose project of its own, with throwaway databases, and removes it
# afterwards.
#
# Usage: bin/test-mta-in-py-e2e-tenants [pytest args]
set -euo pipefail

cd "$(dirname "$0")/.."

export DOCKER_USER="${DOCKER_USER:-$(id -u):$(id -g)}"
export DOCKER_UID="${DOCKER_UID:-$(id -u)}"

project=st-messages-mta-e2e-tenants
secret_a="tenant-a-secret-0123456789abcdef0123456789"
secret_b="tenant-b-secret-0123456789abcdef0123456789"

# Without the host ports the dev stack publishes, so it can run next to it.
override=$(mktemp)
cat > "$override" <<'EOF'
services:
postgresql: {ports: !reset []}
redis: {ports: !reset []}
objectstorage: {ports: !reset []}
EOF

# c reaches b's backend with a's secret: a tenant whose secret is wrong.
# d points at a port nothing listens on: a tenant whose backend is down.
tenants=$(mktemp)
cat > "$tenants" <<EOF
{
"a": {"base_url": "http://$project-backend-a:8000/api/v1.0/", "secret": "$secret_a", "domains": ["tenant-a.example"]},
"b": {"base_url": "http://$project-backend-b:8000/api/v1.0/", "secret": "$secret_b", "domains": ["tenant-b.example"]},
"c": {"base_url": "http://$project-backend-b:8000/api/v1.0/", "secret": "$secret_a", "domains": ["tenant-c.example"]},
"d": {"base_url": "http://$project-backend-a:9/api/v1.0/", "secret": "$secret_a", "domains": ["tenant-d.example"]}
}
EOF
compose=(docker compose -p "$project" -f compose.yaml -f "$override")

cleanup() {
# `down` leaves the containers started with `run`: remove them by label.
docker ps -aq --filter "label=com.docker.compose.project=$project" \
| xargs -r docker rm -f > /dev/null 2>&1 || true
"${compose[@]}" down --volumes --remove-orphans > /dev/null 2>&1 || true
rm -f "$override" "$tenants"
}
trap cleanup EXIT

"${compose[@]}" up -d --wait postgresql redis objectstorage
"${compose[@]}" exec -T postgresql createdb -U user messages_b
for db in messages messages_b; do
"${compose[@]}" run --rm --no-deps -e DB_NAME="$db" backend-db \
python manage.py migrate --no-input
done

# One backend per instance, named rather than aliased: two aliases of
# backend-dev would share one name on the network.
"${compose[@]}" run -d --no-deps --name "$project-backend-a" \
-e DB_NAME=messages -e MDA_API_SECRET="$secret_a" -e OPENSEARCH_INDEX_THREADS=False \
backend-dev > /dev/null
"${compose[@]}" run -d --no-deps --name "$project-backend-b" \
-e DB_NAME=messages_b -e MDA_API_SECRET="$secret_b" -e OPENSEARCH_INDEX_THREADS=False \
backend-dev > /dev/null

# pymta from the working tree, routing by the tenants file.
"${compose[@]}" run -d --no-deps --name "$project-pymta" \
-v "$tenants:/etc/pymta/tenants.json:ro" \
-e EXEC_CMD_ONLY=true \
-e PYMTA_TENANTS_FILE=/etc/pymta/tenants.json \
-e MDA_API_TIMEOUT=30 \
-e PYMTA_METRICS_BIND_PORT=0 \
mta-in-py-test python -m pymta.server > /dev/null

"${compose[@]}" run --rm --no-deps \
-e MTA_E2E_TENANTS_HOST="$project-pymta" \
-e MTA_E2E_TENANT_B_DB=messages_b \
-e OPENSEARCH_INDEX_THREADS=False \
-e WAIT_FOR="$project-backend-a:8000 $project-backend-b:8000 $project-pymta:25" \
backend-dev \
sh -c 'for i in $(seq 1 60); do python -c "
import os, socket
for target in os.environ[\"WAIT_FOR\"].split():
host, port = target.rsplit(\":\", 1)
socket.create_connection((host, int(port)), timeout=1).close()
" 2>/dev/null && break; sleep 1; done; exec pytest -p no:cacheprovider core/tests/mda/test_mta_in_py_tenants_e2e.py "$@"' sh "$@"
146 changes: 146 additions & 0 deletions src/backend/core/tests/mda/test_mta_in_py_tenants_e2e.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,146 @@
"""End to end: one pymta in front of two Messages instances.

Each instance is a backend on a database of its own, with an MDA secret of its
own. pymta routes by the tenants file ``make test-mta-in-py-e2e-tenants``
writes:

- a: the first backend, ``tenant-a.example``
- b: the second backend, ``tenant-b.example``
- c: the second backend, signed with a's secret, ``tenant-c.example``
- d: a backend that does not answer, ``tenant-d.example``

It needs that stack up and is skipped otherwise. The test reads and writes
both databases, so it must never run against ones that hold real data: it only
does when ``MTA_E2E_TENANTS_HOST`` is set, which only that target does.
"""

import contextlib
import email.utils
import os
import smtplib
import time
import uuid

from django.db import connections

import pytest

from core import factories, models

MTA_HOST = os.environ.get("MTA_E2E_TENANTS_HOST", "")
TENANT_B_DB = os.environ.get("MTA_E2E_TENANT_B_DB", "")

pytestmark = pytest.mark.skipif(
not MTA_HOST,
reason="needs pymta and two backends running: make test-mta-in-py-e2e-tenants",
)

HELO = "mx.sender.example"
SENDER = "alice@sender.example"


@contextlib.contextmanager
def _instance(db_name):
"""Point the ORM, signals included, at one instance's database."""
connection = connections["default"]
original = connection.settings_dict["NAME"]
connection.close()
connection.settings_dict["NAME"] = db_name or original
try:
yield
finally:
connection.close()
connection.settings_dict["NAME"] = original


def _mailbox(domain):
mailbox = factories.MailboxFactory(
local_part=f"e2e-{uuid.uuid4().hex[:8]}", domain__name=domain
)
return f"{mailbox.local_part}@{domain}"


@pytest.fixture(scope="module", name="recipients")
def fixture_recipients(django_db_blocker):
"""One mailbox on a, and two on b: one for tenant b, one for tenant c."""
with django_db_blocker.unblock():
with _instance(None):
a = _mailbox("tenant-a.example")
with _instance(TENANT_B_DB):
b = _mailbox("tenant-b.example")
c = _mailbox("tenant-c.example")
return {"a": a, "b": b, "c": c}


def _send(recipients):
"""Send one message to ``recipients`` over SMTP.

Returns its Message-ID and the recipients refused, with their reply.
"""
message_id = f"<{uuid.uuid4().hex}@sender.example>"
message = (
f"From: Alice <{SENDER}>\r\nTo: {', '.join(recipients)}\r\n"
f"Subject: two tenants\r\nMessage-ID: {message_id}\r\n"
f"Date: {email.utils.formatdate()}\r\n\r\nbody\r\n"
).encode()
with smtplib.SMTP(MTA_HOST, 25, local_hostname=HELO, timeout=30) as client:
refused = client.sendmail(SENDER, recipients, message)
return message_id, refused


def _rcpt(address):
"""The reply to RCPT TO for ``address``, in a transaction of its own."""
with smtplib.SMTP(MTA_HOST, 25, local_hostname=HELO, timeout=30) as client:
client.ehlo()
client.mail(SENDER)
return client.rcpt(address)


def _stored_for(message_id):
"""The recipients this instance stored ``message_id`` for."""
deadline = time.monotonic() + 20
while True:
stored = sorted(
inbound.envelope["rcpt_to"]
for inbound in models.InboundMessage.objects.all()
if message_id.encode() in inbound.blob.get_content()
)
if stored or time.monotonic() > deadline:
return stored
time.sleep(0.3)


def test_each_instance_stores_the_message_for_its_own_recipient_only(
recipients, django_db_blocker
):
"""One message, one recipient on each tenant: each instance gets its copy."""
message_id, refused = _send([recipients["a"], recipients["b"]])
assert not refused, refused
with django_db_blocker.unblock():
with _instance(None):
assert _stored_for(message_id) == [recipients["a"]]
with _instance(TENANT_B_DB):
assert _stored_for(message_id) == [recipients["b"]]


def test_a_domain_no_tenant_lists_is_refused():
"""Answered like an unknown mailbox."""
code, text = _rcpt("nobody@unknown.example")
assert (code, text[:5]) == (550, b"5.1.1"), text


def test_a_tenant_signing_with_another_secret_is_deferred(recipients):
"""b's backend refuses a's secret: the sender is told to retry, not refused."""
code, text = _rcpt(recipients["c"])
assert code == 451, text


def test_a_tenant_down_does_not_hold_back_the_others(recipients, django_db_blocker):
"""d's backend does not answer: its recipient is deferred, a's gets the message."""
message_id, refused = _send([recipients["a"], "anyone@tenant-d.example"])
assert [(address, code) for address, (code, _) in refused.items()] == [
("anyone@tenant-d.example", 451)
]
with django_db_blocker.unblock():
with _instance(None):
assert _stored_for(message_id) == [recipients["a"]]
41 changes: 37 additions & 4 deletions src/mta-in/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -118,9 +118,10 @@ make lint-mta-in
# Pure-Python service
make test-mta-in-py
make lint-mta-in-py
make fuzz-mta-in-py # Hypothesis suite, about a minute
make fuzz-mta-in-py-intensive # the same with 10x the examples, about 10 minutes
make test-mta-in-py-e2e # pymta and the real backend together, over SMTP
make fuzz-mta-in-py # Hypothesis suite, about a minute
make fuzz-mta-in-py-intensive # the same with 10x the examples, about 10 minutes
make test-mta-in-py-e2e # pymta and the real backend together, over SMTP
make test-mta-in-py-e2e-tenants # the same, one pymta in front of two backends
```

`make test-mta-in-py` fails under 100% coverage of `src/pymta`, lines and branches. A branch that no test can reach is removed, not excused.
Expand All @@ -139,6 +140,7 @@ Its only runtime dependencies are `httpx` (the MDA client), `PyJWT`, `idna` and
| `session_log.py` | What is logged about a session: the `reject` lines and `session_closed` |
| `handler.py` | What to do with a sender, a recipient, a message: the MDA calls and the per-session budgets |
| `mda_async.py` | The MDA client, its signing and its circuit breaker |
| `tenants.py` | Which MDA a recipient goes to, when several Messages instances share this MTA |
| `limits.py` | Session and DATA slots, per source and in total |
| `controller.py`, `server.py` | The listener, its TLS context, startup and shutdown |
| `healthcheck.py` | The liveness probe the image runs |
Expand Down Expand Up @@ -206,6 +208,8 @@ Grouped as `src/pymta/settings.py` groups them.
| `MDA_API_TIMEOUT` | `30` | Timeout (s) for each phase of an MDA call (connect, each read, each write), and for a recipient check as a whole. A delivery as a whole is bounded by `PYMTA_DATA_TIMEOUT`. A timeout counts toward the breaker on both: it is no verdict on a message, and an MDA that hangs has to be shed |
| `MDA_API_JWT_TTL` | `MDA_API_TIMEOUT + 90` | Lifetime (s) of the JWT signed for each MDA call. Must cover the request plus clock skew against the MDA |
| `MDA_BREAKER_THRESHOLD` | `10` (0 = off) | Consecutive MDA failures before short-circuiting to 451. pymta-only; the milter has no breaker and ignores it |
| `PYMTA_TENANTS_FILE` | unset | Path of a JSON file routing recipients to several MDAs by domain: see [Several Messages instances behind one MTA](#several-messages-instances-behind-one-mta). Set, `MDA_API_BASE_URL` and `MDA_API_SECRET` are not used. pymta only |
| `PYMTA_TENANTS_RELOAD_INTERVAL` | `30` | Seconds between two checks of whether the tenants file changed |
| `MDA_BREAKER_COOLDOWN` | `30` | Seconds the breaker stays open before probing the MDA again. After it, one call goes through as a probe while the others are still answered 451; its success closes the breaker, its failure starts another cooldown. A timeout waiting for a free connection in pymta's own HTTP pool is not counted as an MDA failure. Must be ≥ 1: a zero would reopen the breaker to the very next call, which neuters it rather than disabling it — use the threshold for that |

**SMTP listener and identity**
Expand Down Expand Up @@ -437,7 +441,7 @@ Every configurable limit publishes its value as `pymta_config_limit{name="<setti
| `PYMTA_DATA_TIMEOUT` | ✓ | `reason="data_timeout"`, plus `pymta_disconnects_421_total` when the message was still being received. Also counts a message cut for arriving too slowly while message slots are scarce |
| `PYMTA_COMMAND_TIMEOUT` | ✓ | `reason="command_timeout"`, plus `pymta_disconnects_421_total`. The idle peer is answered 421 before the socket is closed, so it can tell a policy timeout from a network fault |
| stress mode (4/5 of `max_sessions_total`) | — | `pymta_under_stress` is 1 while sessions waiting for a command get the 10 s timeout; `pymta_disconnects_421_total{reason="command_timeout"}` counts the sessions it closes |
| `MDA_BREAKER_THRESHOLD` / `_COOLDOWN` | — | `pymta_mda_breaker_open` is 1 while open; `pymta_mda_request_duration_seconds{result="breaker_open"}` counts the calls it shed |
| `MDA_BREAKER_THRESHOLD` / `_COOLDOWN` | — | `pymta_mda_breaker_open` is 1 while open, and with several tenants `pymta_mda_tenant_breaker_open{tenant=...}` names which; `pymta_mda_request_duration_seconds{result="breaker_open"}` counts the calls it shed |

`pymta_sessions_abandoned_total` counts sessions cut by the `PYMTA_SHUTDOWN_TIMEOUT` drain deadline — non-zero on every rollout means the deadline is too short for your traffic.

Expand Down Expand Up @@ -574,6 +578,35 @@ At startup, and after each reload, `tls_key_types served=ecdsa,rsa` says which k

Mismatched list lengths are refused at startup: the pairing is positional, so a cert would otherwise be loaded against another's key and OpenSSL's complaint names neither variable. An empty entry (a stray comma) is refused for the same reason a half-configured pair is — it would quietly become "STARTTLS off".

### Several Messages instances behind one MTA

One pymta can receive mail for several Messages instances (tenants), each with its own MDA and its own mail domains. Point `PYMTA_TENANTS_FILE` at a JSON object with one entry per tenant:

```json
{
"customer-a": {
"base_url": "http://backend.customer-a.svc:8000/api/v1.0/",
"secret": "<customer-a's MDA_API_SECRET>",
"domains": ["customer-a.example", "lists.customer-a.example"]
},
"customer-b": {
"base_url": "http://backend.customer-b.svc:8000/api/v1.0/",
"secret": "<customer-b's MDA_API_SECRET>",
"domains": ["customer-b.example"]
}
}
```

- **Routing.** A recipient is checked with, and delivered to, the tenant that lists its domain. Domains are compared in lower case and A-labels, so `bücher.example` and `xn--bcher-kva.example` are the same. A domain no tenant lists is answered like an unknown mailbox (`550 5.1.1`, reason `unknown_domain`) and spends the same miss budget. The file decides, not the instance: a domain added in an instance's UI receives no mail until it is listed here.
- **Isolation.** Each tenant has its own secret, so no instance can sign calls to another, and its own circuit breaker, so one instance down does not defer the mail of the others. `pymta_mda_breaker_open` reads 1 while any of them is open, and `pymta_mda_tenant_breaker_open{tenant=...}` tells which one is.
- **One message, several tenants.** The message is delivered once to each tenant, concurrently and within the same `PYMTA_DATA_TIMEOUT`. Each copy's envelope names only that tenant's recipients, so no instance learns of a recipient on another instance that only the envelope names, such as a Bcc. The message itself is passed as sent: its `To` and `Cc` headers still show everyone they list. The sender gets `250` once every tenant has the message, and `554` only if every tenant refused it for good. Anything else gets `451`, and the sender's retry reaches again the tenants that already had the message, the copy is identified by its `Message-ID` and dropped, as a `207` from a single MDA does. (see *Redelivery and duplicates*).
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
- **Reloading.** The file is checked every `PYMTA_TENANTS_RELOAD_INTERVAL` seconds and read again when it changed, which suits a Kubernetes Secret mounted as a volume. Mount it as a directory, not with `subPath`: Kubernetes never updates a `subPath` mount, so the change would wait for a restart. A tenant whose URL and secret are unchanged keeps its connections and its breaker. The client of a tenant removed or changed may still serve a session in flight, so it is released at the next restart only: watch `process_open_fds`. A file that no longer parses, or names one domain under two tenants, is logged as `tenants_reload_failed` and the previous mapping stays in force. At startup, the same mistakes stop the process.
- **Shared limits.** The DATA and session caps (`PYMTA_MAX_CONCURRENT_DATA`, and `PYMTA_MAX_SESSIONS_TOTAL` derived from it) and their per-source shares are global, not per tenant: size them, and the memory, for the summed traffic. One tenant's spike uses capacity the others need.
- **DNS.** The MX of every tenant domain points at this pymta. Each instance shows, checks and can provision the records it expects from `MESSAGES_DNS_RECORDS`, whose MX entries default to `mx1.{MESSAGES_TECHNICAL_DOMAIN}` and `mx2.{MESSAGES_TECHNICAL_DOMAIN}`: make them name the shared MTA, or the instance flags correct setups and provisions wrong ones.
- **Postmaster.** The bare `postmaster` recipient goes to `PYMTA_POSTMASTER_ADDRESS`, so that address's domain must belong to one of the tenants.

The file holds every tenant's secret: mount it from a Secret readable by pymta alone. Without `PYMTA_TENANTS_FILE`, every recipient goes to `MDA_API_BASE_URL` as before. The Postfix image has no equivalent.

## Production checklist

The defaults are tuned for the dev stack. Five things to set before pymta faces the internet; each has a legitimate reason to differ in dev, so the process does not enforce them.
Expand Down
Loading