aboutsummaryrefslogtreecommitdiffstats
path: root/packages/meshbay-hub/src/meshbay_hub
diff options
context:
space:
mode:
authorChristophe Besson <cbesson@gmail.com>2026-09-12 12:14:15 +0200
committerChristophe Besson <cbesson@gmail.com>2026-09-12 16:36:54 +0200
commit6260825bf6d8340549de53905de3bd0b84d97d0a (patch)
tree7c2fc96613f3b499c15e9e2728ffaf7afdf4385b /packages/meshbay-hub/src/meshbay_hub
parent28548dcbde50f7cee471d6962e16115bb87b056f (diff)
downloadmeshbay-6260825bf6d8340549de53905de3bd0b84d97d0a.tar.gz
fix(hub): the mail server is not a relay
The previous commit metered the paths that send mail. It was not enough, and saying it was would have been wrong: a 60-second cooldown per account still allows one stranger a minute — 1440 a day — and registration is open, so "per account" is a bound an attacker buys more of. And there was a third door nobody had counted. POST /v1/users/register an address nobody has verified PATCH /v1/users/me an address nobody has verified, signed in POST /v1/users/password/reset only the address already on file POST /v1/groups/{id}/invite-notify only a registered member's address The widest was the register *resend* branch: no token, no captcha, and the username and address are the caller's own from a moment ago — registering a victim's address once bought the right to mail them at the endpoint's rate limit for as long as the account stayed pending. So the bound moves into `mail.py`, where every message passes one function. `purpose` is keyword-required and checked against a closed list, so a helper that names anything else does not send and one that names nothing is a TypeError rather than an unrestricted send. Under it: - a bound per **recipient**, across every purpose, account and endpoint — what a person being mail-bombed actually experiences, and the only bound that describes it. Keyed on a hash, because this would otherwise be the one place in the hub holding plaintext addresses in memory (S2) - an instance-wide hourly ceiling, which cannot be bought with more accounts - a cooldown on the resend branch, a cooldown and a daily ceiling on the address change, and the IP-log entry that endpoint never wrote — alone among the ones that mail The ceiling on address changes counts IP-log rows, not EmailVerification: the handler deletes this account's unverified rows before writing a new one, so counting those counts one, always. Which is what the first version of it did. Refusals never carry the address: that line goes to the journal. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01T4YmK41VsEURWFdop4EEeT
Diffstat (limited to 'packages/meshbay-hub/src/meshbay_hub')
-rw-r--r--packages/meshbay-hub/src/meshbay_hub/api/users.py51
-rw-r--r--packages/meshbay-hub/src/meshbay_hub/mail.py119
2 files changed, 160 insertions, 10 deletions
diff --git a/packages/meshbay-hub/src/meshbay_hub/api/users.py b/packages/meshbay-hub/src/meshbay_hub/api/users.py
index 05bf075..702d687 100644
--- a/packages/meshbay-hub/src/meshbay_hub/api/users.py
+++ b/packages/meshbay-hub/src/meshbay_hub/api/users.py
@@ -130,6 +130,10 @@ class RefreshRequest(BaseModel):
# ── Endpoints ─────────────────────────────────────────────────────────────────
+# Between two verification mails to one pending account.
+VERIFICATION_RESEND_COOLDOWN = 120
+
+
@router.post("/register", status_code=201)
@limiter.limit("5/minute")
async def register(
@@ -147,9 +151,26 @@ async def register(
if found.status == "pending" and found.email_hash == eh:
# Same person retrying before validation — resend a code.
# No captcha: the initial registration already passed it.
- await _create_and_send_verification(
- db, found, body.email, eh, body.recovery_key)
- await db.commit()
+ #
+ # Which made this the widest of the three mail doors: no token, no
+ # captcha, and the username and address are the caller's own from
+ # a moment ago. Registering a victim's address once bought the
+ # right to mail them at the endpoint's rate limit for ever.
+ # `mail.py` bounds the recipient regardless, and this stops the
+ # door being hammered — the answer is the same either way, which
+ # is the one this endpoint has always given.
+ recent = await db.execute(
+ select(EmailVerification).where(
+ EmailVerification.user_id == found.id,
+ EmailVerification.purpose == "registration",
+ EmailVerification.created_at
+ > datetime.now(timezone.utc)
+ - timedelta(seconds=VERIFICATION_RESEND_COOLDOWN),
+ ))
+ if not recent.first():
+ await _create_and_send_verification(
+ db, found, body.email, eh, body.recovery_key)
+ await db.commit()
return {"user_id": found.id, "email_verification_required": True}
raise HTTPException(status_code=409, detail="Username already taken")
@@ -640,6 +661,7 @@ class UpdateProfileRequest(BaseModel):
# the account's, not the caller's IP: the point is the mailbox on the receiving
# end, and an IP is not what fills it.
EMAIL_CHANGE_COOLDOWN = 60
+MAX_EMAIL_CHANGES_PER_DAY = 3
@router.patch("/me")
@@ -680,6 +702,27 @@ async def update_profile(
status_code=429,
detail="A code was just sent. Wait a minute before asking again.")
+ # And a ceiling per day, because the cooldown alone still allows one
+ # stranger a minute — 1440 a day, from one account, on a hub where
+ # registration is open. This is the only path where a signed-in
+ # account chooses the recipient, so it is the only one that needs it.
+ #
+ # Counted from the IP log, not from EmailVerification: the block below
+ # deletes this account's unverified rows before writing a new one, so
+ # counting those would have counted one, always. (Which is what the
+ # first version of this did.) The log entry is worth having for its
+ # own sake — this endpoint wrote none, alone among the ones that mail.
+ today = await db.execute(
+ select(func.count()).select_from(IPLog).where(
+ IPLog.user_id == current_user.id,
+ IPLog.event == "email_change_request",
+ IPLog.timestamp > datetime.now(timezone.utc) - timedelta(days=1),
+ ))
+ if (today.scalar() or 0) >= MAX_EMAIL_CHANGES_PER_DAY:
+ raise HTTPException(
+ status_code=429,
+ detail="Too many address changes today. Try again tomorrow.")
+
# Check that no other active/pending account uses this email
dup = await db.execute(
select(User).where(
@@ -709,6 +752,8 @@ async def update_profile(
user_id=current_user.id,
expires_at=datetime.now(timezone.utc) + timedelta(seconds=VERIFICATION_TTL),
))
+ db.add(IPLog(user_id=current_user.id, event="email_change_request",
+ ip_address=client_ip(request)))
await db.flush()
await mail.send_off_loop(mail.send_email_change_code, new_email, code)
pending_email = new_email
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))