feat(auth): verify email domain MX before sending magic links
Bot sign-ups with rotating temp-mail domains (onldm.net -> 10minutemail's SMTP) and nonexistent addresses were bouncing every magic link back into the support inbox and hurting sender reputation. - email_policy.mx_verdict(): resolve the domain's MX (A fallback per RFC 5321) and reject when nothing can receive mail or when the MX target belongs to known disposable-mail infrastructure - catches the rotating front domains the static blocklist can't keep up with. Cached per domain, fails open on resolver trouble. - auth: per-IP rate limit on magic-link requests (bots rotate addresses, not IPs). - blocklist: add onldm.net; pin dnspython (already transitive via email-validator).
This commit is contained in:
parent
ab86e41846
commit
a76decd56f
5 changed files with 216 additions and 8 deletions
|
|
@ -27,6 +27,7 @@ JWT_ALGO = "HS256"
|
||||||
JWT_TTL_DAYS = 30
|
JWT_TTL_DAYS = 30
|
||||||
MAGIC_TTL_MINUTES = 15
|
MAGIC_TTL_MINUTES = 15
|
||||||
MAGIC_RATE_LIMIT = 3 # per email
|
MAGIC_RATE_LIMIT = 3 # per email
|
||||||
|
MAGIC_RATE_LIMIT_IP = 10 # per IP, any email — bots rotate addresses, not IPs
|
||||||
MAGIC_RATE_WINDOW_MIN = 15
|
MAGIC_RATE_WINDOW_MIN = 15
|
||||||
# Only accept attribution for an account this young. Both sign-in flows post it
|
# Only accept attribution for an account this young. Both sign-in flows post it
|
||||||
# right after the redirect, so anything older is a returning user whose "source"
|
# right after the redirect, so anything older is a returning user whose "source"
|
||||||
|
|
@ -154,15 +155,29 @@ class MagicVerifyRequest(BaseModel):
|
||||||
async def request_magic_link(payload: MagicLinkRequest, request: Request):
|
async def request_magic_link(payload: MagicLinkRequest, request: Request):
|
||||||
from .emails import send_magic_link_email
|
from .emails import send_magic_link_email
|
||||||
|
|
||||||
|
disposable_msg = (
|
||||||
|
"That email provider isn't supported. Please use a permanent "
|
||||||
|
"address (Gmail, Outlook, iCloud…) or sign in with Google.")
|
||||||
|
|
||||||
# Block temp-mail before doing anything else — the free plan is open to
|
# Block temp-mail before doing anything else — the free plan is open to
|
||||||
# email accounts now, so disposable domains would be a free-minute farm.
|
# email accounts now, so disposable domains would be a free-minute farm.
|
||||||
if email_policy.is_disposable(payload.email):
|
if email_policy.is_disposable(payload.email):
|
||||||
raise HTTPException(status_code=400, detail=(
|
raise HTTPException(status_code=400, detail=disposable_msg)
|
||||||
"That email provider isn't supported. Please use a permanent "
|
|
||||||
"address (Gmail, Outlook, iCloud…) or sign in with Google."))
|
|
||||||
|
|
||||||
# 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
|
||||||
|
# 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."))
|
||||||
|
|
||||||
|
client_ip = request.client.host if request.client else None
|
||||||
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)
|
||||||
|
|
@ -175,13 +190,23 @@ async def request_magic_link(payload: MagicLinkRequest, request: Request):
|
||||||
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:
|
||||||
|
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)
|
raw_token = secrets.token_urlsafe(32)
|
||||||
token_hash = hashlib.sha256(raw_token.encode()).hexdigest()
|
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=request.client.host if request.client else None,
|
request_ip=client_ip,
|
||||||
))
|
))
|
||||||
|
|
||||||
link = f"{settings.frontend_url}/#/auth/verify?ml={raw_token}"
|
link = f"{settings.frontend_url}/#/auth/verify?ml={raw_token}"
|
||||||
|
|
|
||||||
|
|
@ -5,6 +5,7 @@
|
||||||
# sign-ups. Add new ones here as they appear.
|
# sign-ups. Add new ones here as they appear.
|
||||||
|
|
||||||
# --- Observed in our own DB ---
|
# --- Observed in our own DB ---
|
||||||
|
onldm.net
|
||||||
web-library.net
|
web-library.net
|
||||||
diarshop.com
|
diarshop.com
|
||||||
hidepost.net
|
hidepost.net
|
||||||
|
|
|
||||||
|
|
@ -1,12 +1,17 @@
|
||||||
"""Email hygiene for sign-up: block disposable domains, normalize aliases.
|
"""Email hygiene for sign-up: block disposable domains, normalize aliases,
|
||||||
|
verify the domain can actually receive mail.
|
||||||
|
|
||||||
Two abuse vectors this closes, now that the free plan is open to email (not
|
Three abuse vectors this closes, now that the free plan is open to email (not
|
||||||
just Google) accounts:
|
just Google) accounts:
|
||||||
* temp-mail domains → free-minute farms (blocklist below).
|
* temp-mail domains → free-minute farms (blocklist below, plus MX-target
|
||||||
|
matching for the rotating front domains the blocklist can't keep up with).
|
||||||
* provider aliases (gmail dots / +tags) → one address becomes infinite
|
* provider aliases (gmail dots / +tags) → one address becomes infinite
|
||||||
accounts → normalized to a single canonical form.
|
accounts → normalized to a single canonical form.
|
||||||
|
* nonexistent addresses/domains → every magic link bounces back into the
|
||||||
|
support inbox and burns sender reputation with PrivateEmail.
|
||||||
"""
|
"""
|
||||||
import os
|
import os
|
||||||
|
import time
|
||||||
|
|
||||||
_DOMAINS_FILE = os.path.join(os.path.dirname(os.path.abspath(__file__)),
|
_DOMAINS_FILE = os.path.join(os.path.dirname(os.path.abspath(__file__)),
|
||||||
"disposable_domains.txt")
|
"disposable_domains.txt")
|
||||||
|
|
@ -62,3 +67,94 @@ def normalize_email(email: str) -> str:
|
||||||
|
|
||||||
def disposable_count() -> int:
|
def disposable_count() -> int:
|
||||||
return len(_DISPOSABLE)
|
return len(_DISPOSABLE)
|
||||||
|
|
||||||
|
|
||||||
|
# --------------------------------------------------------------------------- #
|
||||||
|
# MX verification
|
||||||
|
# --------------------------------------------------------------------------- #
|
||||||
|
# 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",
|
||||||
|
}
|
||||||
|
|
||||||
|
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_MAX = 10_000 # bots probing random domains must not grow it unbounded
|
||||||
|
_mx_cache = {} # domain -> (verdict, monotonic expiry)
|
||||||
|
|
||||||
|
|
||||||
|
def classify_mx_hosts(hosts) -> str:
|
||||||
|
"""Verdict from a domain's MX target hostnames."""
|
||||||
|
hosts = [str(h).rstrip(".").lower() for h in hosts]
|
||||||
|
# RFC 7505 null MX (a single "." target): the domain declares it takes no mail.
|
||||||
|
if not any(hosts):
|
||||||
|
return MX_NONE
|
||||||
|
for host in hosts:
|
||||||
|
if any(host == d or host.endswith("." + d) for d in _DISPOSABLE_MX):
|
||||||
|
return MX_DISPOSABLE
|
||||||
|
return MX_OK
|
||||||
|
|
||||||
|
|
||||||
|
async def _resolve(domain: str, rtype: str):
|
||||||
|
import dns.asyncresolver
|
||||||
|
|
||||||
|
resolver = dns.asyncresolver.Resolver()
|
||||||
|
resolver.lifetime = _MX_TIMEOUT
|
||||||
|
return await resolver.resolve(domain, rtype)
|
||||||
|
|
||||||
|
|
||||||
|
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.
|
||||||
|
"""
|
||||||
|
import dns.resolver
|
||||||
|
|
||||||
|
domain = (email or "").rsplit("@", 1)[-1].strip().lower()
|
||||||
|
if not domain:
|
||||||
|
return MX_NONE
|
||||||
|
now = time.monotonic()
|
||||||
|
hit = _mx_cache.get(domain)
|
||||||
|
if hit and hit[1] > now:
|
||||||
|
return hit[0]
|
||||||
|
|
||||||
|
try:
|
||||||
|
answers = await _resolve(domain, "MX")
|
||||||
|
verdict = classify_mx_hosts(r.exchange for r in answers)
|
||||||
|
except dns.resolver.NXDOMAIN:
|
||||||
|
verdict = MX_NONE
|
||||||
|
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
|
||||||
|
except Exception:
|
||||||
|
verdict = MX_OK
|
||||||
|
|
||||||
|
if len(_mx_cache) >= _MX_CACHE_MAX:
|
||||||
|
_mx_cache.clear()
|
||||||
|
_mx_cache[domain] = (verdict, now + _MX_CACHE_TTL)
|
||||||
|
return verdict
|
||||||
|
|
|
||||||
|
|
@ -9,3 +9,4 @@ authlib==1.3.2
|
||||||
itsdangerous==2.2.0
|
itsdangerous==2.2.0
|
||||||
PyJWT==2.10.1
|
PyJWT==2.10.1
|
||||||
email-validator==2.2.0
|
email-validator==2.2.0
|
||||||
|
dnspython==2.7.0
|
||||||
|
|
|
||||||
|
|
@ -1,4 +1,8 @@
|
||||||
"""Disposable-domain blocking and email alias normalization."""
|
"""Disposable-domain blocking, email alias normalization and MX verification."""
|
||||||
|
import asyncio
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
from cloud import email_policy as ep
|
from cloud import email_policy as ep
|
||||||
|
|
||||||
|
|
||||||
|
|
@ -10,6 +14,7 @@ class TestDisposable:
|
||||||
def test_db_observed_domains_blocked(self):
|
def test_db_observed_domains_blocked(self):
|
||||||
assert ep.is_disposable("a@luckfeed.com") is True
|
assert ep.is_disposable("a@luckfeed.com") is True
|
||||||
assert ep.is_disposable("b@web-library.net") is True
|
assert ep.is_disposable("b@web-library.net") is True
|
||||||
|
assert ep.is_disposable("c@onldm.net") is True
|
||||||
|
|
||||||
def test_real_providers_allowed(self):
|
def test_real_providers_allowed(self):
|
||||||
for e in ("real@gmail.com", "u@outlook.com", "u@icloud.com", "u@yandex.ru"):
|
for e in ("real@gmail.com", "u@outlook.com", "u@icloud.com", "u@yandex.ru"):
|
||||||
|
|
@ -38,3 +43,83 @@ class TestNormalize:
|
||||||
|
|
||||||
def test_lowercased(self):
|
def test_lowercased(self):
|
||||||
assert ep.normalize_email("USER@Example.COM") == "user@example.com"
|
assert ep.normalize_email("USER@Example.COM") == "user@example.com"
|
||||||
|
|
||||||
|
|
||||||
|
class TestClassifyMxHosts:
|
||||||
|
def test_disposable_infrastructure_caught(self):
|
||||||
|
# onldm.net-style rotating front domain: MX points at the real provider.
|
||||||
|
assert ep.classify_mx_hosts(["prd-smtp.10minutemail.com."]) == ep.MX_DISPOSABLE
|
||||||
|
assert ep.classify_mx_hosts(["mail.mailinator.com"]) == ep.MX_DISPOSABLE
|
||||||
|
|
||||||
|
def test_null_mx_means_no_mail(self):
|
||||||
|
assert ep.classify_mx_hosts(["."]) == ep.MX_NONE
|
||||||
|
|
||||||
|
def test_real_provider_ok(self):
|
||||||
|
assert ep.classify_mx_hosts(["aspmx.l.google.com."]) == ep.MX_OK
|
||||||
|
assert ep.classify_mx_hosts(["mx1.privateemail.com", "mx2.privateemail.com"]) == ep.MX_OK
|
||||||
|
|
||||||
|
def test_suffix_match_not_substring(self):
|
||||||
|
assert ep.classify_mx_hosts(["not10minutemail.com"]) == ep.MX_OK
|
||||||
|
|
||||||
|
def test_any_disposable_host_taints(self):
|
||||||
|
hosts = ["aspmx.l.google.com.", "backup.guerrillamail.com."]
|
||||||
|
assert ep.classify_mx_hosts(hosts) == ep.MX_DISPOSABLE
|
||||||
|
|
||||||
|
|
||||||
|
class TestMxVerdict:
|
||||||
|
"""The resolver is monkeypatched: no network in tests."""
|
||||||
|
|
||||||
|
def setup_method(self):
|
||||||
|
ep._mx_cache.clear()
|
||||||
|
|
||||||
|
def test_fail_open_on_resolver_trouble(self, monkeypatch):
|
||||||
|
pytest.importorskip("dns")
|
||||||
|
|
||||||
|
async def boom(domain, rtype):
|
||||||
|
raise RuntimeError("resolver down")
|
||||||
|
|
||||||
|
monkeypatch.setattr(ep, "_resolve", boom)
|
||||||
|
assert asyncio.run(ep.mx_verdict("u@example.com")) == ep.MX_OK
|
||||||
|
|
||||||
|
def test_nxdomain_is_no_mx(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@no-such-domain.example")) == ep.MX_NONE
|
||||||
|
|
||||||
|
def test_no_mx_falls_back_to_a_record(self, monkeypatch):
|
||||||
|
dns = pytest.importorskip("dns")
|
||||||
|
import dns.resolver
|
||||||
|
|
||||||
|
async def no_mx_but_a(domain, rtype):
|
||||||
|
if rtype == "MX":
|
||||||
|
raise dns.resolver.NoAnswer()
|
||||||
|
return ["1.2.3.4"]
|
||||||
|
|
||||||
|
monkeypatch.setattr(ep, "_resolve", no_mx_but_a)
|
||||||
|
assert asyncio.run(ep.mx_verdict("u@a-record-only.example")) == ep.MX_OK
|
||||||
|
|
||||||
|
def test_verdict_is_cached_per_domain(self, monkeypatch):
|
||||||
|
pytest.importorskip("dns")
|
||||||
|
calls = []
|
||||||
|
|
||||||
|
async def counting(domain, rtype):
|
||||||
|
calls.append(domain)
|
||||||
|
|
||||||
|
class R:
|
||||||
|
exchange = "prd-smtp.10minutemail.com."
|
||||||
|
|
||||||
|
return [R()]
|
||||||
|
|
||||||
|
monkeypatch.setattr(ep, "_resolve", counting)
|
||||||
|
assert asyncio.run(ep.mx_verdict("a@onldm.net")) == ep.MX_DISPOSABLE
|
||||||
|
assert asyncio.run(ep.mx_verdict("b@onldm.net")) == ep.MX_DISPOSABLE
|
||||||
|
assert calls == ["onldm.net"]
|
||||||
|
|
||||||
|
def test_empty_email_is_no_mx(self):
|
||||||
|
pytest.importorskip("dns")
|
||||||
|
assert asyncio.run(ep.mx_verdict("")) == ep.MX_NONE
|
||||||
|
|
|
||||||
Loading…
Reference in a new issue