aboutsummaryrefslogtreecommitdiffstats
path: root/packages/meshbay-hub/src/meshbay_hub/mail.py
diff options
context:
space:
mode:
Diffstat (limited to 'packages/meshbay-hub/src/meshbay_hub/mail.py')
-rw-r--r--packages/meshbay-hub/src/meshbay_hub/mail.py119
1 files changed, 112 insertions, 7 deletions
diff --git a/packages/meshbay-hub/src/meshbay_hub/mail.py b/packages/meshbay-hub/src/meshbay_hub/mail.py
index 8373204..5d13b8d 100644
--- a/packages/meshbay-hub/src/meshbay_hub/mail.py
+++ b/packages/meshbay-hub/src/meshbay_hub/mail.py
@@ -3,15 +3,107 @@ MeshBay Hub — email sending via localhost Postfix.
Postfix listens on loopback only (inet_interfaces = loopback-only), so no
authentication is needed. See docs/MAIL-SERVER.md for the full setup.
+
+**No authentication is needed** is exactly why everything below exists. The
+hub can emit mail from its own domain to anywhere, and three API paths reach
+that ability — two of them at an address the caller types. Unbounded, that is
+an open relay wearing the instance's reputation, so the bounds are here, in
+the one function every send passes through, rather than at the call sites
+where the next one added would forget them (`AV9`–`AV10`, §13.5b).
"""
import asyncio
+import hashlib
import logging
import smtplib
+import time
from email.message import EmailMessage
log = logging.getLogger(__name__)
+
+class MailRefused(Exception):
+ """The gate below declined to send. Never carries the address."""
+
+
+# The complete list of reasons this hub will ever send mail. A `send_*`
+# function that names anything else does not send — and one that names nothing
+# is a TypeError, because `purpose` is keyword-required.
+#
+# registration confirm an address at sign-up
+# password_reset a code to the address already on file for that account
+# invite tell a registered member they were invited to a group
+# email_change confirm a new address before it replaces the old one
+#
+# Only `registration` and `email_change` can reach an address this hub has no
+# prior relationship with. Both are necessary; both are why the per-destination
+# bound below is keyed on the recipient rather than on who asked.
+ALLOWED_PURPOSES = frozenset({
+ "registration", "password_reset", "invite", "email_change"})
+
+# Per recipient, across every purpose, every account and every IP. This is the
+# bound that matters: it is what a person being mail-bombed actually
+# experiences, and no combination of accounts, addresses or endpoints moves it.
+DESTINATION_COOLDOWN_SECONDS = 120
+DESTINATION_DAILY_CAP = 5
+
+# Instance-wide ceiling. Registration is open, so "per account" is a bound an
+# attacker buys more of; this one cannot be bought. Sized far above a real
+# hub's traffic — meshbay.org sends single-digit mails a day — and low enough
+# that being used as a relay is not worth the trouble.
+HOURLY_BUDGET = 200
+
+# Single-process state, like `_connected_nodes` and `_node_groups` next door:
+# the hub serves on one worker (`server.workers` defaults to 1) and the
+# signaling registries already require it. A restart clears these, which costs
+# at most one burst and is not a security decision — unlike the denylist,
+# which persists for exactly that reason (S3).
+_destinations: dict[str, tuple[float, int, float]] = {} # key → (last, day count, day start)
+_hour: tuple[float, int] = (0.0, 0) # (window start, count)
+
+
+def _destination_key(address: str) -> str:
+ """A stable handle for one recipient that is not the address itself.
+
+ Hashed because this dict is the one place in the hub that would otherwise
+ hold a list of plaintext addresses in memory — the rest of the codebase
+ goes to the trouble of encrypting them at rest (S2).
+ """
+ return hashlib.sha256(address.strip().lower().encode()).hexdigest()[:32]
+
+
+def _budget_or_refuse(purpose: str, address: str) -> None:
+ """Raise MailRefused unless this hub may send this, to this person, now."""
+ global _hour
+
+ if purpose not in ALLOWED_PURPOSES:
+ raise MailRefused(f"not a purpose this hub sends mail for: {purpose!r}")
+
+ now = time.monotonic()
+ start, count = _hour
+ if now - start >= 3600:
+ start, count = now, 0
+ if count >= HOURLY_BUDGET:
+ _hour = (start, count)
+ raise MailRefused("the hub's hourly mail budget is spent")
+
+ key = _destination_key(address)
+ last, sent_today, day_start = _destinations.get(key, (0.0, 0, now))
+ if now - day_start >= 86400:
+ sent_today, day_start = 0, now
+ if last and now - last < DESTINATION_COOLDOWN_SECONDS:
+ raise MailRefused("too soon since the last mail to this recipient")
+ if sent_today >= DESTINATION_DAILY_CAP:
+ raise MailRefused("this recipient has had its daily allowance")
+
+ if len(_destinations) > 10_000:
+ for k, (_, _, started) in list(_destinations.items()):
+ if now - started >= 86400:
+ _destinations.pop(k, None)
+
+ _destinations[key] = (now, sent_today + 1, day_start)
+ _hour = (start, count + 1)
+
_hub_domain: str = "meshbay.org"
_hub_url: str = "https://meshbay.org"
@@ -22,14 +114,27 @@ def configure(hub_id: str) -> None:
_hub_url = f"https://{hub_id}"
-def _send(msg: EmailMessage) -> bool:
- """Blocking. Every caller in an async handler must use `send_off_loop`."""
+def _send(msg: EmailMessage, *, purpose: str) -> bool:
+ """Blocking. Every caller in an async handler must use `send_off_loop`.
+
+ The gate is here rather than in `send_off_loop` so that it cannot be
+ stepped around: a new `send_*` helper, a script, a test — everything that
+ puts a message on the wire comes through this function, and `purpose` is
+ keyword-required so forgetting it is a TypeError rather than an
+ unrestricted send.
+ """
+ try:
+ _budget_or_refuse(purpose, msg["To"] or "")
+ except MailRefused as refusal:
+ # Never the address: this line goes to the journal.
+ log.warning("Mail refused (%s): %s", purpose, refusal)
+ return False
try:
with smtplib.SMTP("localhost", 25, timeout=10) as s:
s.send_message(msg)
return True
except Exception:
- log.exception("Failed to send email to %s", msg["To"])
+ log.exception("Failed to send email to %s", _mask_email(msg["To"] or ""))
return False
@@ -86,7 +191,7 @@ def send_verification_code(to: str, code: str, recovery_key: str | None = None)
msg["To"] = to
msg["Subject"] = f"MeshBay — Your verification code: {code}"
msg.set_content(body)
- _send(msg)
+ _send(msg, purpose="registration")
log.info("Verification code sent to %s (recovery_key=%s)",
_mask_email(to), bool(recovery_key))
@@ -106,7 +211,7 @@ def send_email_change_code(to: str, code: str) -> None:
"\n"
f"{_hub_url}\n"
)
- _send(msg)
+ _send(msg, purpose="email_change")
log.info("Email change code sent to %s", _mask_email(to))
@@ -132,7 +237,7 @@ def send_password_reset_code(to: str, code: str) -> None:
"\n"
f"{_hub_url}\n"
)
- _send(msg)
+ _send(msg, purpose="password_reset")
log.info("Passphrase reset code sent to %s", _mask_email(to))
@@ -153,7 +258,7 @@ def send_invite_notification(
"\n"
f"{_hub_url}\n"
)
- _send(msg)
+ _send(msg, purpose="invite")
log.info("Invite notification sent to %s", _mask_email(to))