fix(auth): harden MX verification after code review

Review findings on the MX-gate commit, addressed:

- Rate limits now run BEFORE the DNS work, and the attempt row is
  inserted before the MX gate, so rejected junk-domain floods count
  toward both limits instead of getting unlimited free DNS lookups.
- Existing accounts bypass the MX gate: it protects sign-up only, so a
  domain whose MX later matches the disposable list can't lock an owner
  out of their account.
- RFC 5321 implicit MX now also checks AAAA (IPv6-only mail domains
  were falsely rejected).
- Error-derived verdicts cache for 60s instead of 1h: a transient
  NXDOMAIN no longer pins a lockout, a resolver blip no longer
  whitelists a domain for an hour.
- One shared resolver with an LRU record cache (was: new resolver +
  resolv.conf read per lookup); verdict cache evicts FIFO instead of
  full clear.
- MX blocklist moved to disposable_mx.txt, same loader and ops workflow
  as disposable_domains.txt (the two lists were already drifting).
- Both rate-limit counts merged into one FILTER query; distinct 429
  message for the per-IP limit (shared-NAT lockouts diagnosable).
- Index on (request_ip, created_at) + 30-day token purge in the
  retention sweeper. NOTE: schema is create_all-only, prod needs:
  CREATE INDEX IF NOT EXISTS ix_magic_ip_created
    ON magic_link_tokens (request_ip, created_at);
This commit is contained in:
juancarlos.cavero 2026-08-13 10:07:20 +02:00
parent a76decd56f
commit e4331467e5
6 changed files with 160 additions and 67 deletions

View file

@ -15,7 +15,7 @@ from typing import Optional
import jwt import jwt
from fastapi import APIRouter, Request, HTTPException from fastapi import APIRouter, Request, HTTPException
from pydantic import BaseModel, EmailStr from pydantic import BaseModel, EmailStr
from sqlalchemy import select, func, and_ from sqlalchemy import select, func
from .config import settings from .config import settings
from . import config, database, metering, email_policy from . import config, database, metering, email_policy
@ -167,53 +167,74 @@ async def request_magic_link(payload: MagicLinkRequest, request: Request):
# Normalize (strip +tags / Gmail dots) so aliases can't mint extra accounts. # Normalize (strip +tags / Gmail dots) so aliases can't mint extra accounts.
email = email_policy.normalize_email(payload.email) email = email_policy.normalize_email(payload.email)
# The static list can't keep up with rotating temp-mail domains, and bots # Best-effort: uvicorn resolves this from X-Forwarded-For (trusted "*" in
# sign up with domains that don't receive mail at all — both come back as # the Dockerfile), which a client can forge — good enough against the bots
# bounces that flood the support inbox and burn sender reputation. # we actually see, but not a security boundary.
verdict = await email_policy.mx_verdict(email)
if verdict == email_policy.MX_DISPOSABLE:
raise HTTPException(status_code=400, detail=disposable_msg)
if verdict == email_policy.MX_NONE:
raise HTTPException(status_code=400, detail=(
"That email domain can't receive mail. Please double-check the address."))
client_ip = request.client.host if request.client else None client_ip = request.client.host if request.client else None
raw_token = secrets.token_urlsafe(32)
token_hash = hashlib.sha256(raw_token.encode()).hexdigest()
async with database.session() as session: async with database.session() as session:
async with session.begin(): async with session.begin():
window_start = _now() - timedelta(minutes=MAGIC_RATE_WINDOW_MIN) window_start = _now() - timedelta(minutes=MAGIC_RATE_WINDOW_MIN)
recent = (await session.execute( recent, recent_ip = (await session.execute(
select(func.count(MagicLinkToken.id)).where(and_( select(
MagicLinkToken.email == email, func.count(MagicLinkToken.id).filter(MagicLinkToken.email == email),
MagicLinkToken.created_at >= window_start, func.count(MagicLinkToken.id).filter(MagicLinkToken.request_ip == client_ip),
)) ).where(MagicLinkToken.created_at >= window_start)
)).scalar_one() )).one()
if recent >= MAGIC_RATE_LIMIT: if recent >= MAGIC_RATE_LIMIT:
raise HTTPException(status_code=429, detail="Too many login attempts. Try again in a few minutes.") raise HTTPException(status_code=429, detail="Too many login attempts. Try again in a few minutes.")
if client_ip and recent_ip >= MAGIC_RATE_LIMIT_IP:
raise HTTPException(status_code=429, detail=(
"Too many sign-in attempts from your network. Try again in a few minutes."))
if client_ip: # Recorded BEFORE the MX gate so rejected attempts still count
recent_ip = (await session.execute( # toward both limits — otherwise a junk-domain flood never trips
select(func.count(MagicLinkToken.id)).where(and_( # them. The raw token is only ever emailed after the gate passes.
MagicLinkToken.request_ip == client_ip,
MagicLinkToken.created_at >= window_start,
))
)).scalar_one()
if recent_ip >= MAGIC_RATE_LIMIT_IP:
raise HTTPException(status_code=429, detail="Too many login attempts. Try again in a few minutes.")
raw_token = secrets.token_urlsafe(32)
token_hash = hashlib.sha256(raw_token.encode()).hexdigest()
session.add(MagicLinkToken( session.add(MagicLinkToken(
email=email, email=email,
token_hash=token_hash, token_hash=token_hash,
expires_at=_now() + timedelta(minutes=MAGIC_TTL_MINUTES), expires_at=_now() + timedelta(minutes=MAGIC_TTL_MINUTES),
request_ip=client_ip, request_ip=client_ip,
)) ))
account_exists = (await session.execute(
select(User.id).where(User.email == email)
)).scalar_one_or_none() is not None
# The static list can't keep up with rotating temp-mail domains, and bots
# sign up with domains that don't receive mail at all — both come back as
# bounces that flood the support inbox and burn sender reputation. The
# gate protects sign-UP only: an existing account must keep working even
# if its domain's MX later matches the disposable list or resolves badly.
if not account_exists:
verdict = await email_policy.mx_verdict(email)
if verdict == email_policy.MX_DISPOSABLE:
raise HTTPException(status_code=400, detail=disposable_msg)
if verdict == email_policy.MX_NONE:
raise HTTPException(status_code=400, detail=(
"That email domain can't receive mail. Please double-check the address."))
link = f"{settings.frontend_url}/#/auth/verify?ml={raw_token}" link = f"{settings.frontend_url}/#/auth/verify?ml={raw_token}"
await send_magic_link_email(email, link) await send_magic_link_email(email, link)
return {"ok": True} return {"ok": True}
async def purge_stale_magic_tokens():
"""Drop token rows too old to matter for auth or rate limiting.
Called from the retention sweeper: without it the table grows with every
sign-in forever and the rate-limit counts scan an ever-larger window.
"""
from sqlalchemy import delete
cutoff = _now() - timedelta(days=30)
async with database.session() as session:
async with session.begin():
await session.execute(
delete(MagicLinkToken).where(MagicLinkToken.created_at < cutoff))
@router.post("/api/auth/magic-link/verify") @router.post("/api/auth/magic-link/verify")
async def verify_magic_link(payload: MagicVerifyRequest): async def verify_magic_link(payload: MagicVerifyRequest):
token_hash = hashlib.sha256(payload.token.encode()).hexdigest() token_hash = hashlib.sha256(payload.token.encode()).hexdigest()

18
cloud/disposable_mx.txt Normal file
View file

@ -0,0 +1,18 @@
# MX-target domains of disposable/temp-mail providers (one per line, lowercase).
# Comments (#) and blank lines ignored. Matched as a suffix against the MX
# hostnames of a sign-up domain: front domains rotate (onldm.net was one of
# 10minutemail's) but they all point MX at the provider's real SMTP hosts,
# which stay put. Add the MX target here when a new front domain shows up in
# the bounces (dig +short MX <domain>).
10minutemail.com
1secmail.com
dropmail.me
generator.email
guerrillamail.com
harakirimail.com
mail.tm
maildrop.cc
mailinator.com
mohmal.com
temp-mail.org
yopmail.com

View file

@ -25,10 +25,10 @@ _PLUS_ALIASING = _DOT_INSENSITIVE | {
} }
def _load_disposable() -> set: def _load_list(path: str) -> set:
domains = set() domains = set()
try: try:
with open(_DOMAINS_FILE, encoding="utf-8") as f: with open(path, encoding="utf-8") as f:
for line in f: for line in f:
line = line.strip().lower() line = line.strip().lower()
if line and not line.startswith("#"): if line and not line.startswith("#"):
@ -38,7 +38,7 @@ def _load_disposable() -> set:
return domains return domains
_DISPOSABLE = _load_disposable() _DISPOSABLE = _load_list(_DOMAINS_FILE)
def is_disposable(email: str) -> bool: def is_disposable(email: str) -> bool:
@ -75,30 +75,22 @@ def disposable_count() -> int:
# Disposable providers rotate their front domains faster than any blocklist # Disposable providers rotate their front domains faster than any blocklist
# (onldm.net was one of 10minutemail's), but every front domain points its MX # (onldm.net was one of 10minutemail's), but every front domain points its MX
# at the provider's real SMTP hosts, which stay put. Matching the MX target # at the provider's real SMTP hosts, which stay put. Matching the MX target
# catches the whole rotation at once. Suffix match on these domains. # catches the whole rotation at once. Suffix match against the domains in
_DISPOSABLE_MX = { # disposable_mx.txt — same ops workflow as the sign-up blocklist above.
"10minutemail.com", _MX_FILE = os.path.join(os.path.dirname(os.path.abspath(__file__)),
"1secmail.com", "disposable_mx.txt")
"dropmail.me", _DISPOSABLE_MX = _load_list(_MX_FILE)
"generator.email",
"guerrillamail.com",
"harakirimail.com",
"mail.tm",
"maildrop.cc",
"mailinator.com",
"mohmal.com",
"temp-mail.org",
"yopmail.com",
}
MX_OK = "ok" MX_OK = "ok"
MX_NONE = "no_mx" MX_NONE = "no_mx"
MX_DISPOSABLE = "disposable_mx" MX_DISPOSABLE = "disposable_mx"
_MX_TIMEOUT = 4.0 # seconds; a slow resolver must not stall sign-in _MX_TIMEOUT = 4.0 # seconds; a slow resolver must not stall sign-in
_MX_CACHE_TTL = 3600.0 _MX_CACHE_TTL = 3600.0 # verdicts computed from an actual DNS answer
_MX_ERROR_TTL = 60.0 # error-derived verdicts: a blip must not stick for 1h
_MX_CACHE_MAX = 10_000 # bots probing random domains must not grow it unbounded _MX_CACHE_MAX = 10_000 # bots probing random domains must not grow it unbounded
_mx_cache = {} # domain -> (verdict, monotonic expiry) _mx_cache = {} # domain -> (verdict, monotonic expiry)
_resolver = None
def classify_mx_hosts(hosts) -> str: def classify_mx_hosts(hosts) -> str:
@ -113,19 +105,47 @@ def classify_mx_hosts(hosts) -> str:
return MX_OK return MX_OK
async def _resolve(domain: str, rtype: str): def _get_resolver():
# One shared resolver: reads resolv.conf once, and its LRU cache honors
# each record's real TTL, so a junk-domain flood can't force live lookups
# for the hot legit domains (gmail, outlook, …).
global _resolver
import dns.asyncresolver import dns.asyncresolver
import dns.resolver
resolver = dns.asyncresolver.Resolver() if _resolver is None:
resolver.lifetime = _MX_TIMEOUT r = dns.asyncresolver.Resolver()
return await resolver.resolve(domain, rtype) r.lifetime = _MX_TIMEOUT
r.cache = dns.resolver.LRUCache()
_resolver = r
return _resolver
async def _resolve(domain: str, rtype: str):
return await _get_resolver().resolve(domain, rtype)
async def _implicit_mx(domain: str):
"""RFC 5321 implicit MX: no MX record → deliverable if A or AAAA exists."""
import dns.resolver
for rtype in ("A", "AAAA"):
try:
await _resolve(domain, rtype)
return MX_OK, _MX_CACHE_TTL
except (dns.resolver.NXDOMAIN, dns.resolver.NoAnswer):
continue
except Exception:
return MX_OK, _MX_ERROR_TTL
return MX_NONE, _MX_ERROR_TTL
async def mx_verdict(email: str) -> str: async def mx_verdict(email: str) -> str:
"""MX_OK / MX_NONE / MX_DISPOSABLE for the address's domain. """MX_OK / MX_NONE / MX_DISPOSABLE for the address's domain.
Fails open (MX_OK) on resolver trouble — a DNS blip must never lock real Fails open (MX_OK) on resolver trouble — a DNS blip must never lock real
users out of sign-in. users out of sign-in — and error-derived verdicts are cached only briefly
so a transient NXDOMAIN can't pin a lockout for an hour.
""" """
import dns.resolver import dns.resolver
@ -137,24 +157,20 @@ async def mx_verdict(email: str) -> str:
if hit and hit[1] > now: if hit and hit[1] > now:
return hit[0] return hit[0]
ttl = _MX_CACHE_TTL
try: try:
answers = await _resolve(domain, "MX") answers = await _resolve(domain, "MX")
verdict = classify_mx_hosts(r.exchange for r in answers) verdict = classify_mx_hosts(r.exchange for r in answers)
except dns.resolver.NXDOMAIN: except dns.resolver.NXDOMAIN:
verdict = MX_NONE verdict, ttl = MX_NONE, _MX_ERROR_TTL
except dns.resolver.NoAnswer: except dns.resolver.NoAnswer:
# No MX published: RFC 5321 falls back to the A record for delivery. verdict, ttl = await _implicit_mx(domain)
try:
await _resolve(domain, "A")
verdict = MX_OK
except (dns.resolver.NXDOMAIN, dns.resolver.NoAnswer):
verdict = MX_NONE
except Exception:
verdict = MX_OK
except Exception: except Exception:
verdict = MX_OK verdict, ttl = MX_OK, _MX_ERROR_TTL
if len(_mx_cache) >= _MX_CACHE_MAX: # FIFO-evict one entry when full (dicts keep insertion order) — a flood of
_mx_cache.clear() # junk domains must not wipe the whole cache at once.
_mx_cache[domain] = (verdict, now + _MX_CACHE_TTL) while len(_mx_cache) >= _MX_CACHE_MAX:
_mx_cache.pop(next(iter(_mx_cache)))
_mx_cache[domain] = (verdict, now + ttl)
return verdict return verdict

View file

@ -35,7 +35,13 @@ class MagicLinkToken(Base):
used_at = Column(DateTime(timezone=True), nullable=True) used_at = Column(DateTime(timezone=True), nullable=True)
request_ip = Column(Text, nullable=True) request_ip = Column(Text, nullable=True)
created_at = Column(DateTime(timezone=True), server_default=func.now()) created_at = Column(DateTime(timezone=True), server_default=func.now())
__table_args__ = (Index("ix_magic_email_created", "email", "created_at"),) __table_args__ = (
Index("ix_magic_email_created", "email", "created_at"),
# NOTE: schema is create_all-only; on an existing DB this index must be
# applied by hand: CREATE INDEX IF NOT EXISTS ix_magic_ip_created
# ON magic_link_tokens (request_ip, created_at);
Index("ix_magic_ip_created", "request_ip", "created_at"),
)
class Subscription(Base): class Subscription(Base):

View file

@ -399,6 +399,8 @@ async def _sweeper_loop():
await warn_free_expiring() await warn_free_expiring()
await purge_expired() await purge_expired()
await purge_free_expired() await purge_free_expired()
from .auth import purge_stale_magic_tokens
await purge_stale_magic_tokens()
except asyncio.CancelledError: except asyncio.CancelledError:
break break
except Exception as e: except Exception as e:

View file

@ -103,6 +103,36 @@ class TestMxVerdict:
monkeypatch.setattr(ep, "_resolve", no_mx_but_a) monkeypatch.setattr(ep, "_resolve", no_mx_but_a)
assert asyncio.run(ep.mx_verdict("u@a-record-only.example")) == ep.MX_OK assert asyncio.run(ep.mx_verdict("u@a-record-only.example")) == ep.MX_OK
def test_no_mx_falls_back_to_aaaa_record(self, monkeypatch):
dns = pytest.importorskip("dns")
import dns.resolver
async def ipv6_only(domain, rtype):
if rtype == "AAAA":
return ["::1"]
raise dns.resolver.NoAnswer()
monkeypatch.setattr(ep, "_resolve", ipv6_only)
assert asyncio.run(ep.mx_verdict("u@ipv6-only.example")) == ep.MX_OK
def test_error_verdicts_cached_briefly(self, monkeypatch):
dns = pytest.importorskip("dns")
import dns.resolver
async def nx(domain, rtype):
raise dns.resolver.NXDOMAIN()
monkeypatch.setattr(ep, "_resolve", nx)
assert asyncio.run(ep.mx_verdict("u@transient-blip.example")) == ep.MX_NONE
import time
_, expiry = ep._mx_cache["transient-blip.example"]
# A transient NXDOMAIN must not pin the lockout for the full hour.
assert expiry - time.monotonic() <= ep._MX_ERROR_TTL + 1
def test_mx_blocklist_loaded_from_file(self):
assert "10minutemail.com" in ep._DISPOSABLE_MX
assert len(ep._DISPOSABLE_MX) >= 10
def test_verdict_is_cached_per_domain(self, monkeypatch): def test_verdict_is_cached_per_domain(self, monkeypatch):
pytest.importorskip("dns") pytest.importorskip("dns")
calls = [] calls = []