Repository navigation
✨(pymta) dispatch inbound mail to several Messages instances #876
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
LoanR
wants to merge
11
commits into
suitenumerique:main
Choose a base branch
from
yaal-coop:feat/mta-in-multi-tenant
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from 8 commits
Commits
Show all changes
11 commits
Select commit
Hold shift + click to select a range
b089367
✨(pymta) route recipients to several MDAs by domain
unteem 62b1df8
✅(pymta) build MDA clients in tenants router test
LoanR d589d2d
✅(pymta) check tenant calls are signed
LoanR ec0782f
✅(pymta) deliver to multiple tenants concurrently
LoanR 268ba13
✅(pymta) deliver accepted recipient anyway
LoanR 706e7f4
🔊(pymta) log tenant in client MDA
LoanR 5d57589
📈(pymta) gauge circuit breaker for each tenant
LoanR 841eb3c
✅(pymta) test e2e pymta with multiple tenants
LoanR 00b4e52
📝(pymta) limit tenant privacy to the envelope
LoanR e1c9a23
🐛(pymta) deliver each recipient through the client that accepted it
LoanR 3414155
📝(pymta) clarify no Message-Id ends on copy
LoanR File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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
146
src/backend/core/tests/mda/test_mta_in_py_tenants_e2e.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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"]] |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.