From e4331467e5d2352fd8c75535584e6e1e09b482b3 Mon Sep 17 00:00:00 2001 From: "juancarlos.cavero" Date: Thu, 13 Aug 2026 10:07:20 +0200 Subject: [PATCH] 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); --- cloud/auth.py | 79 +++++++++++++++++++++------------ cloud/disposable_mx.txt | 18 ++++++++ cloud/email_policy.py | 90 ++++++++++++++++++++++---------------- cloud/models.py | 8 +++- cloud/videos.py | 2 + tests/test_email_policy.py | 30 +++++++++++++ 6 files changed, 160 insertions(+), 67 deletions(-) create mode 100644 cloud/disposable_mx.txt diff --git a/cloud/auth.py b/cloud/auth.py index f9c7af9..2e977cf 100644 --- a/cloud/auth.py +++ b/cloud/auth.py @@ -15,7 +15,7 @@ from typing import Optional import jwt from fastapi import APIRouter, Request, HTTPException from pydantic import BaseModel, EmailStr -from sqlalchemy import select, func, and_ +from sqlalchemy import select, func from .config import settings 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. email = email_policy.normalize_email(payload.email) - # 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. - 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.")) - + # Best-effort: uvicorn resolves this from X-Forwarded-For (trusted "*" in + # the Dockerfile), which a client can forge — good enough against the bots + # we actually see, but not a security boundary. 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 session.begin(): window_start = _now() - timedelta(minutes=MAGIC_RATE_WINDOW_MIN) - recent = (await session.execute( - select(func.count(MagicLinkToken.id)).where(and_( - MagicLinkToken.email == email, - MagicLinkToken.created_at >= window_start, - )) - )).scalar_one() + recent, recent_ip = (await session.execute( + select( + func.count(MagicLinkToken.id).filter(MagicLinkToken.email == email), + func.count(MagicLinkToken.id).filter(MagicLinkToken.request_ip == client_ip), + ).where(MagicLinkToken.created_at >= window_start) + )).one() if recent >= MAGIC_RATE_LIMIT: 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: - recent_ip = (await session.execute( - select(func.count(MagicLinkToken.id)).where(and_( - 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() + # Recorded BEFORE the MX gate so rejected attempts still count + # toward both limits — otherwise a junk-domain flood never trips + # them. The raw token is only ever emailed after the gate passes. session.add(MagicLinkToken( email=email, token_hash=token_hash, expires_at=_now() + timedelta(minutes=MAGIC_TTL_MINUTES), 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}" await send_magic_link_email(email, link) 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") async def verify_magic_link(payload: MagicVerifyRequest): token_hash = hashlib.sha256(payload.token.encode()).hexdigest() diff --git a/cloud/disposable_mx.txt b/cloud/disposable_mx.txt new file mode 100644 index 0000000..ea9d248 --- /dev/null +++ b/cloud/disposable_mx.txt @@ -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 ). +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 diff --git a/cloud/email_policy.py b/cloud/email_policy.py index d41ca3e..05dd85a 100644 --- a/cloud/email_policy.py +++ b/cloud/email_policy.py @@ -25,10 +25,10 @@ _PLUS_ALIASING = _DOT_INSENSITIVE | { } -def _load_disposable() -> set: +def _load_list(path: str) -> set: domains = set() try: - with open(_DOMAINS_FILE, encoding="utf-8") as f: + with open(path, encoding="utf-8") as f: for line in f: line = line.strip().lower() if line and not line.startswith("#"): @@ -38,7 +38,7 @@ def _load_disposable() -> set: return domains -_DISPOSABLE = _load_disposable() +_DISPOSABLE = _load_list(_DOMAINS_FILE) def is_disposable(email: str) -> bool: @@ -75,30 +75,22 @@ def disposable_count() -> int: # Disposable providers rotate their front domains faster than any blocklist # (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 -# catches the whole rotation at once. Suffix match on these domains. -_DISPOSABLE_MX = { - "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", -} +# catches the whole rotation at once. Suffix match against the domains in +# disposable_mx.txt — same ops workflow as the sign-up blocklist above. +_MX_FILE = os.path.join(os.path.dirname(os.path.abspath(__file__)), + "disposable_mx.txt") +_DISPOSABLE_MX = _load_list(_MX_FILE) MX_OK = "ok" MX_NONE = "no_mx" MX_DISPOSABLE = "disposable_mx" _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 = {} # domain -> (verdict, monotonic expiry) +_resolver = None def classify_mx_hosts(hosts) -> str: @@ -113,19 +105,47 @@ def classify_mx_hosts(hosts) -> str: 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.resolver - resolver = dns.asyncresolver.Resolver() - resolver.lifetime = _MX_TIMEOUT - return await resolver.resolve(domain, rtype) + if _resolver is None: + r = dns.asyncresolver.Resolver() + 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: """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 - 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 @@ -137,24 +157,20 @@ async def mx_verdict(email: str) -> str: if hit and hit[1] > now: return hit[0] + ttl = _MX_CACHE_TTL try: answers = await _resolve(domain, "MX") verdict = classify_mx_hosts(r.exchange for r in answers) except dns.resolver.NXDOMAIN: - verdict = MX_NONE + verdict, ttl = MX_NONE, _MX_ERROR_TTL except dns.resolver.NoAnswer: - # No MX published: RFC 5321 falls back to the A record for delivery. - try: - await _resolve(domain, "A") - verdict = MX_OK - except (dns.resolver.NXDOMAIN, dns.resolver.NoAnswer): - verdict = MX_NONE - except Exception: - verdict = MX_OK + verdict, ttl = await _implicit_mx(domain) except Exception: - verdict = MX_OK + verdict, ttl = MX_OK, _MX_ERROR_TTL - if len(_mx_cache) >= _MX_CACHE_MAX: - _mx_cache.clear() - _mx_cache[domain] = (verdict, now + _MX_CACHE_TTL) + # FIFO-evict one entry when full (dicts keep insertion order) — a flood of + # junk domains must not wipe the whole cache at once. + while len(_mx_cache) >= _MX_CACHE_MAX: + _mx_cache.pop(next(iter(_mx_cache))) + _mx_cache[domain] = (verdict, now + ttl) return verdict diff --git a/cloud/models.py b/cloud/models.py index 2b7042d..1fe0073 100644 --- a/cloud/models.py +++ b/cloud/models.py @@ -35,7 +35,13 @@ class MagicLinkToken(Base): used_at = Column(DateTime(timezone=True), nullable=True) request_ip = Column(Text, nullable=True) 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): diff --git a/cloud/videos.py b/cloud/videos.py index 0e27775..4bac00f 100644 --- a/cloud/videos.py +++ b/cloud/videos.py @@ -399,6 +399,8 @@ async def _sweeper_loop(): await warn_free_expiring() await purge_expired() await purge_free_expired() + from .auth import purge_stale_magic_tokens + await purge_stale_magic_tokens() except asyncio.CancelledError: break except Exception as e: diff --git a/tests/test_email_policy.py b/tests/test_email_policy.py index 8aeb688..f720093 100644 --- a/tests/test_email_policy.py +++ b/tests/test_email_policy.py @@ -103,6 +103,36 @@ class TestMxVerdict: monkeypatch.setattr(ep, "_resolve", no_mx_but_a) 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): pytest.importorskip("dns") calls = []