sitcod3 commited on
Commit
f5afa05
·
verified ·
1 Parent(s): 9fa1941

Upload folder using huggingface_hub

Browse files
.env.example CHANGED
@@ -39,17 +39,31 @@ MAX_BULK_EMAILS=10000
39
  RATE_LIMIT_PER_MINUTE=60
40
  USE_PROXIES=false
41
 
42
- # --- Mailbox verification provider (Layers 5 + 6) ---
43
- # Hugging Face Spaces blocks outbound port 25, so direct SMTP + catch-all
44
- # cannot run there. Set MV_API_KEY to delegate those layers to MillionVerifier.
45
- # auto (default): use the API when MV_API_KEY is set, else direct SMTP
46
- # api : force the verification API
47
- # local : force direct SMTP (requires port-25 egress)
48
- MAILBOX_PROVIDER=auto
 
 
 
 
 
 
 
49
  MV_API_KEY=
50
  MV_TIMEOUT=10
51
- # Circuit breaker for direct SMTP on a blocked host: after N consecutive
52
- # connection failures, fail fast for the cooldown instead of burning timeout
53
- # per address.
54
- SMTP_FAIL_THRESHOLD=3
55
- SMTP_COOLDOWN_SECONDS=300
 
 
 
 
 
 
 
 
39
  RATE_LIMIT_PER_MINUTE=60
40
  USE_PROXIES=false
41
 
42
+ # --- Mailbox verification engine (Layers 5 + 6) ---
43
+ # The validator is AUTONOMOUS by default: it probes recipient MX servers
44
+ # directly on port 25 with its own connection-reusing SMTP engine. No vendor
45
+ # account, API key, or per-check fee is required.
46
+ #
47
+ # IMPORTANT: port 25 must be open outbound. Most cloud PaaS (Hugging Face
48
+ # Spaces, AWS Lambda, Cloudflare Workers) BLOCK it. If outbound 25 is blocked,
49
+ # the engine still runs but reports every mailbox as smtp_unreachable (honest
50
+ # "risky", refunded) — it will never fake a verdict. Run on a VPS/host with
51
+ # port-25 egress for real mailbox verdicts.
52
+ MAILBOX_PROVIDER=auto # auto | local(=autonomous) | api
53
+ # Optional: route Layers 5-6 through a third-party API instead of own SMTP.
54
+ # Off by default so the engine stays independent even if a key is present.
55
+ PREFER_API_PROVIDER=false
56
  MV_API_KEY=
57
  MV_TIMEOUT=10
58
+
59
+ # SMTP identity used in the probe dialogue. Use a real, resolvable hostname with
60
+ # a matching PTR record on a production host — strict receivers reject generic
61
+ # HELO names and that degrades accuracy.
62
+ SMTP_HELO_DOMAIN=validator.local
63
+ SMTP_MAIL_FROM=probe@validator.local
64
+
65
+ # Catch-all is a domain property: cache the verdict for 72h.
66
+ CATCH_ALL_TTL_SECONDS=259200
67
+ # Per-MX-host session cap and overall bulk concurrency.
68
+ MAX_CONNECTIONS_PER_HOST=2
69
+ BULK_CONCURRENCY=20
app/config.py CHANGED
@@ -73,13 +73,27 @@ class Settings(BaseSettings):
73
  # third-party verification API instead. "auto" uses the API when an API key
74
  # is present, else falls back to direct SMTP. "local"/"api" force a provider.
75
  mailbox_provider: str = "auto" # auto | local | api
76
- mv_api_key: str = "" # MillionVerifier real-time API key
 
 
 
 
 
 
 
 
77
  mv_timeout: int = 10 # per-check provider timeout (seconds)
78
  # Circuit breaker: after this many consecutive direct-SMTP connection
79
  # failures (blocked egress), fail fast for `smtp_cooldown_seconds` instead
80
  # of burning the full timeout on every address.
81
  smtp_fail_threshold: int = 3
82
  smtp_cooldown_seconds: int = 300
 
 
 
 
 
 
83
 
84
  # Celery
85
  celery_broker_url: str = "redis://localhost:6379/1"
 
73
  # third-party verification API instead. "auto" uses the API when an API key
74
  # is present, else falls back to direct SMTP. "local"/"api" force a provider.
75
  mailbox_provider: str = "auto" # auto | local | api
76
+ # Independence by default: the engine uses its own SMTP probing even when a
77
+ # third-party key happens to be present. Set True only to deliberately route
78
+ # the mailbox layers through the API.
79
+ prefer_api_provider: bool = False
80
+ # Public HELO/MX identity used in the SMTP dialogue. A real, resolvable
81
+ # hostname with matching PTR improves acceptance by strict receivers.
82
+ smtp_helo_domain: str = "validator.local"
83
+ smtp_mail_from: str = "probe@validator.local"
84
+ mv_api_key: str = "" # MillionVerifier real-time API key (optional)
85
  mv_timeout: int = 10 # per-check provider timeout (seconds)
86
  # Circuit breaker: after this many consecutive direct-SMTP connection
87
  # failures (blocked egress), fail fast for `smtp_cooldown_seconds` instead
88
  # of burning the full timeout on every address.
89
  smtp_fail_threshold: int = 3
90
  smtp_cooldown_seconds: int = 300
91
+ # Catch-all is a domain property — cache the verdict for 72h so a bulk list
92
+ # does not re-probe the same domain for every address.
93
+ catch_all_ttl_seconds: int = 72 * 3600
94
+ # Per-MX-host SMTP session cap and global concurrency for bulk runs.
95
+ max_connections_per_host: int = 2
96
+ bulk_concurrency: int = 20
97
 
98
  # Celery
99
  celery_broker_url: str = "redis://localhost:6379/1"
app/validator/mailbox_provider.py CHANGED
@@ -119,6 +119,57 @@ class MillionVerifierProvider(MailboxProvider):
119
  return None, 0.0
120
 
121
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
122
  class LocalSmtpProvider(MailboxProvider):
123
  """Direct port-25 SMTP with a circuit breaker for blocked egress."""
124
 
@@ -191,12 +242,19 @@ class LocalSmtpProvider(MailboxProvider):
191
 
192
 
193
  def resolve_provider() -> MailboxProvider:
 
 
 
 
 
 
 
194
  mode = (settings.mailbox_provider or "auto").strip().lower()
195
  if mode == "api":
196
  return MillionVerifierProvider()
197
  if mode == "local":
198
- return LocalSmtpProvider()
199
- # auto
200
- if settings.mv_api_key:
201
  return MillionVerifierProvider()
202
- return LocalSmtpProvider()
 
119
  return None, 0.0
120
 
121
 
122
+ class AutonomousSmtpProvider(MailboxProvider):
123
+ """The self-contained engine: own SMTP probing, no third-party service.
124
+
125
+ Wraps the MX-grouped batch verifier (reused sessions, per-domain catch-all
126
+ caching, greylist awareness). This is the default provider — the validator
127
+ must work with no vendor account, key, or per-check fee.
128
+ """
129
+
130
+ name = "autonomous"
131
+
132
+ def __init__(self, batch=None):
133
+ if batch is None:
134
+ from .mx_batch import CatchAllCache, MxBatchVerifier
135
+
136
+ batch = MxBatchVerifier(
137
+ timeout=settings.smtp_timeout,
138
+ helo_domain=settings.smtp_helo_domain,
139
+ mail_from=settings.smtp_mail_from,
140
+ catch_all_cache=CatchAllCache(
141
+ ttl_seconds=settings.catch_all_ttl_seconds
142
+ ),
143
+ )
144
+ self.batch = batch
145
+
146
+ async def verify(self, email: str, mx_host: str) -> SMTPResult:
147
+ results = self.batch.verify_batch([(email, mx_host)])
148
+ return results.get(email) or SMTPResult(
149
+ verified=None, error="engine returned no result"
150
+ )
151
+
152
+ async def catch_all(
153
+ self, domain: str, mx_host: str
154
+ ) -> Tuple[Optional[bool], float]:
155
+ """Probe a gibberish local part to learn whether the domain accepts all."""
156
+ gibberish = f"{GIBBERISH_LOCAL}@{domain}"
157
+ results = self.batch.verify_batch([(gibberish, mx_host)])
158
+ probe = results.get(gibberish)
159
+ if probe is None:
160
+ return None, 0.0
161
+ if probe.verified is True:
162
+ # The domain accepted a random address -> catch-all.
163
+ return True, 0.9
164
+ if probe.verified is False:
165
+ return False, 0.9
166
+ # Inconclusive: distinguish a detected catch-all from a dead probe.
167
+ err = (probe.error or "").lower()
168
+ if "catch_all" in err:
169
+ return True, 0.95
170
+ return None, 0.0
171
+
172
+
173
  class LocalSmtpProvider(MailboxProvider):
174
  """Direct port-25 SMTP with a circuit breaker for blocked egress."""
175
 
 
242
 
243
 
244
  def resolve_provider() -> MailboxProvider:
245
+ """Pick the mailbox provider.
246
+
247
+ The validator is autonomous by default: it uses its own SMTP engine and
248
+ needs no third-party account. The verification API is opt-in only
249
+ (`mailbox_provider="api"`, or `prefer_api_provider=True` with a key set) —
250
+ a stray key must never silently re-route the engine through a vendor.
251
+ """
252
  mode = (settings.mailbox_provider or "auto").strip().lower()
253
  if mode == "api":
254
  return MillionVerifierProvider()
255
  if mode == "local":
256
+ return AutonomousSmtpProvider()
257
+ # auto → own engine, unless API use was explicitly preferred and configured.
258
+ if settings.mv_api_key and getattr(settings, "prefer_api_provider", False):
259
  return MillionVerifierProvider()
260
+ return AutonomousSmtpProvider()
app/validator/mx_batch.py ADDED
@@ -0,0 +1,201 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """MX/domain-grouped batch verification — the throughput core of the engine.
2
+
3
+ Opens one SMTP session per domain (not per address), probes a high-entropy
4
+ gibberish address once to learn whether the domain is catch-all, caches that
5
+ domain-level fact, and only then probes the real mailboxes.
6
+
7
+ Why this matters:
8
+ - A TCP + EHLO handshake dominates the cost of a probe, so reusing one session
9
+ for many RCPTs is the difference between a 10k list taking minutes vs hours.
10
+ - Catch-all is a *domain* property, so probing it once per domain (and caching
11
+ it for 24-72h) removes a redundant probe for every other address there.
12
+ - On a known catch-all domain no per-address RCPT can distinguish a real
13
+ mailbox from a fake one, so the honest answer is "unverifiable" — returned
14
+ without burning a connection.
15
+
16
+ Every remote failure is data, never an exception: one dead host cannot abort a
17
+ bulk job.
18
+ """
19
+ from __future__ import annotations
20
+
21
+ import random
22
+ import time
23
+ from dataclasses import dataclass
24
+ from typing import Callable, Iterable, Optional
25
+
26
+ from ..models import SMTPResult
27
+ from .mx_intel import classify_mx
28
+ from .smtp_client import RcptOutcome, SmtpConnection
29
+
30
+ DEFAULT_CATCH_ALL_TTL = 72 * 3600 # 72h — catch-all status is stable
31
+
32
+
33
+ @dataclass
34
+ class CatchAllCache:
35
+ """Per-domain catch-all memory.
36
+
37
+ `None` means "probe could not decide" and is deliberately NOT cached — a
38
+ failed probe must not be remembered as a decision in either direction.
39
+ """
40
+
41
+ ttl_seconds: int = DEFAULT_CATCH_ALL_TTL
42
+
43
+ def __post_init__(self) -> None:
44
+ self._store: dict[str, tuple[bool, float]] = {}
45
+
46
+ def put(self, domain: str, value: Optional[bool]) -> None:
47
+ if value is None:
48
+ return
49
+ self._store[domain.lower()] = (bool(value), time.time() + self.ttl_seconds)
50
+
51
+ def get(self, domain: str) -> Optional[bool]:
52
+ item = self._store.get(domain.lower())
53
+ if item is None:
54
+ return None
55
+ value, expires = item
56
+ if time.time() >= expires:
57
+ self._store.pop(domain.lower(), None)
58
+ return None
59
+ return value
60
+
61
+ def clear(self) -> None:
62
+ self._store.clear()
63
+
64
+
65
+ def _gibberish(domain: str) -> str:
66
+ token = f"{random.getrandbits(48):012x}"
67
+ return f"xq{token}@{domain}"
68
+
69
+
70
+ class MxBatchVerifier:
71
+ """Verify many (email, mx_host) pairs with domain-level session reuse."""
72
+
73
+ def __init__(
74
+ self,
75
+ connection_factory: Optional[Callable[..., object]] = None,
76
+ *,
77
+ timeout: float = 10.0,
78
+ helo_domain: str = "validator.local",
79
+ mail_from: str = "probe@validator.local",
80
+ catch_all_cache: Optional[CatchAllCache] = None,
81
+ max_connections_per_host: int = 2,
82
+ ):
83
+ self.timeout = timeout
84
+ self.helo_domain = helo_domain
85
+ self.mail_from = mail_from
86
+ self.catch_all_cache = catch_all_cache or CatchAllCache()
87
+ self.max_connections_per_host = max_connections_per_host
88
+ self._factory = connection_factory or (
89
+ lambda host, **kw: SmtpConnection(host, **kw)
90
+ )
91
+
92
+ def _new_connection(self, mx_host: str):
93
+ return self._factory(
94
+ mx_host,
95
+ timeout=self.timeout,
96
+ helo_domain=self.helo_domain,
97
+ mail_from=self.mail_from,
98
+ )
99
+
100
+ def verify_batch(
101
+ self, pairs: Iterable[tuple[str, str]]
102
+ ) -> dict[str, SMTPResult]:
103
+ """Verify pairs of (email, mx_host). Returns email -> SMTPResult."""
104
+ pairs = list(pairs)
105
+ if not pairs:
106
+ return {}
107
+
108
+ # Group by (domain, mx) — catch-all is a domain property, and one domain
109
+ # maps to one MX host, so this is the natural session unit.
110
+ groups: dict[tuple[str, str], list[str]] = {}
111
+ for email, mx_host in pairs:
112
+ domain = email.rsplit("@", 1)[-1].lower()
113
+ groups.setdefault((domain, mx_host), []).append(email)
114
+
115
+ results: dict[str, SMTPResult] = {}
116
+ for (domain, mx_host), emails in groups.items():
117
+ results.update(self._verify_domain(domain, mx_host, emails))
118
+ return results
119
+
120
+ def _verify_domain(
121
+ self, domain: str, mx_host: str, emails: list[str]
122
+ ) -> dict[str, SMTPResult]:
123
+ cached = self.catch_all_cache.get(domain)
124
+
125
+ # Known catch-all: no per-address probe can confirm a mailbox here.
126
+ if cached is True:
127
+ return {
128
+ e: SMTPResult(verified=None, error=f"catch_all (cached): {domain}")
129
+ for e in emails
130
+ }
131
+
132
+ out: dict[str, SMTPResult] = {}
133
+ conn = self._new_connection(mx_host)
134
+ try:
135
+ if not conn.open():
136
+ return {
137
+ e: SMTPResult(
138
+ verified=None,
139
+ error=f"smtp_unreachable: {mx_host}",
140
+ )
141
+ for e in emails
142
+ }
143
+
144
+ if cached is None:
145
+ ca = conn.probe(_gibberish(domain))
146
+ if ca.accepted:
147
+ self.catch_all_cache.put(domain, True)
148
+ for e in emails:
149
+ out[e] = SMTPResult(
150
+ verified=None,
151
+ error=f"catch_all: {domain} accepts every recipient",
152
+ )
153
+ return out
154
+ if ca.permanent_reject:
155
+ self.catch_all_cache.put(domain, False)
156
+ # else inconclusive -> do not cache, fall through and probe.
157
+
158
+ policy = classify_mx(mx_host)
159
+ for email in emails:
160
+ out[email] = self._interpret(conn.probe(email), policy, domain)
161
+ except Exception as exc: # defensive: never let one group kill the job
162
+ for email in emails:
163
+ out.setdefault(
164
+ email, SMTPResult(verified=None, error=f"probe_error: {exc}")
165
+ )
166
+ finally:
167
+ try:
168
+ conn.quit()
169
+ except Exception:
170
+ pass
171
+ return out
172
+
173
+ @staticmethod
174
+ def _interpret(outcome: RcptOutcome, policy, domain: str) -> SMTPResult:
175
+ if outcome.transport_error:
176
+ return SMTPResult(
177
+ verified=None, error=f"transport_error: {outcome.error or 'unknown'}"
178
+ )
179
+ if outcome.accepted:
180
+ if policy.accepts_all:
181
+ # Microsoft 365 / gateways accept everything and bounce later —
182
+ # a 250 here is not proof of a mailbox.
183
+ return SMTPResult(
184
+ verified=None,
185
+ error=f"accept_all_provider ({policy.provider}): rcpt not conclusive",
186
+ )
187
+ return SMTPResult(
188
+ verified=True, smtp_code=250, smtp_message=outcome.message[:400]
189
+ )
190
+ if outcome.permanent_reject:
191
+ return SMTPResult(
192
+ verified=False,
193
+ smtp_code=outcome.code,
194
+ smtp_message=outcome.message[:400],
195
+ )
196
+ # 4xx greylist or unexpected code: inconclusive, retryable.
197
+ return SMTPResult(
198
+ verified=None,
199
+ smtp_code=outcome.code,
200
+ error=f"inconclusive: {outcome.message[:200] or outcome.code}",
201
+ )
app/validator/mx_intel.py ADDED
@@ -0,0 +1,105 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Receiving-provider intelligence — the knowledge layer of the autonomous engine.
2
+
3
+ A raw SMTP probe returns different *meanings* depending on who is answering:
4
+
5
+ - Google Workspace / consumer Gmail reject unknown mailboxes at RCPT with
6
+ 550 5.1.1, so a 250 there is real evidence the mailbox exists.
7
+ - Microsoft 365 (and Mimecast/Proofpoint gateways in front of it) accept
8
+ *every* recipient at SMTP time and emit the bounce asynchronously hours
9
+ later. A 250 from those hosts proves nothing, so it must never be read as
10
+ "mailbox verified".
11
+ - Many smaller hosts are catch-all by accident (cPanel defaults).
12
+
13
+ Recognising the provider from its MX host lets the engine apply the correct
14
+ policy instead of treating every 250 as success. This is the standard technique
15
+ used by commercial validators, implemented here with no third-party API.
16
+ """
17
+ from __future__ import annotations
18
+
19
+ import re
20
+ from dataclasses import dataclass
21
+
22
+ # MX host suffix -> (provider, accepts_all, trusts_rcpt)
23
+ # accepts_all: accepts every recipient at RCPT (250 is not proof)
24
+ # trusts_rcpt: a 250/550 at RCPT is meaningful evidence
25
+ _MX_PATTERNS: tuple[tuple[str, str, bool, bool], ...] = (
26
+ ("google.com", "google", False, True),
27
+ ("googlemail.com", "google", False, True),
28
+ ("outlook.com", "microsoft365", True, False),
29
+ ("protection.outlook.com", "microsoft365", True, False),
30
+ ("office365.com", "microsoft365", True, False),
31
+ ("mimecast.com", "mimecast", True, False),
32
+ ("pphosted.com", "proofpoint", True, False),
33
+ ("proofpoint.com", "proofpoint", True, False),
34
+ ("barracudanetworks.com", "barracuda", True, False),
35
+ ("yahoodns.net", "yahoo", False, True),
36
+ ("yahoo.com", "yahoo", False, True),
37
+ ("aol.com", "yahoo", False, True),
38
+ ("icloud.com", "apple", False, True),
39
+ ("me.com", "apple", False, True),
40
+ ("zoho.com", "zoho", False, True),
41
+ ("zoho.eu", "zoho", False, True),
42
+ ("protonmail.ch", "proton", False, True),
43
+ ("proton.me", "proton", False, True),
44
+ ("secureserver.net", "godaddy", False, False),
45
+ ("fastmail.com", "fastmail", False, True),
46
+ ("messagingengine.com", "fastmail", False, True),
47
+ ("yandex.net", "yandex", False, True),
48
+ ("qq.com", "tencent", False, True),
49
+ ("163.com", "netease", False, True),
50
+ ("amazonaws.com", "amazon", False, False),
51
+ ("amazonses.com", "amazon", False, False),
52
+ )
53
+
54
+ _RCPT_CODE_RE = re.compile(r"^\s*(\d{3})")
55
+
56
+
57
+ @dataclass(frozen=True)
58
+ class MxPolicy:
59
+ """How to interpret an SMTP response from a given receiving host."""
60
+
61
+ provider: str
62
+ trusts_rcpt: bool
63
+ accepts_all: bool
64
+
65
+
66
+ def classify_mx(mx_host: str) -> MxPolicy:
67
+ """Identify the receiving provider from its MX hostname.
68
+
69
+ Unknown hosts get a neutral policy: not assumed malicious, but a lone 250
70
+ is not accepted as proof — the catch-all probe must corroborate it.
71
+ """
72
+ host = (mx_host or "").strip().lower().rstrip(".")
73
+ for suffix, provider, accepts_all, trusts_rcpt in _MX_PATTERNS:
74
+ if host == suffix or host.endswith("." + suffix):
75
+ return MxPolicy(
76
+ provider=provider, trusts_rcpt=trusts_rcpt, accepts_all=accepts_all
77
+ )
78
+ return MxPolicy(provider="unknown", trusts_rcpt=False, accepts_all=False)
79
+
80
+
81
+ def parse_rcpt_code(response: str) -> int | None:
82
+ """Extract the numeric SMTP status from a response line, or None."""
83
+ match = _RCPT_CODE_RE.match(response or "")
84
+ return int(match.group(1)) if match else None
85
+
86
+
87
+ def is_greylist_code(code: int | None) -> bool:
88
+ """4xx — temporary (greylisting / rate limit / mailbox busy)."""
89
+ return code is not None and 400 <= code < 500
90
+
91
+
92
+ def is_permanent_reject(code: int | None) -> bool:
93
+ """5xx — permanent failure (mailbox does not exist, domain refuses)."""
94
+ return code is not None and 500 <= code < 600
95
+
96
+
97
+ def should_retry(code: int | None, *, transport_error: bool = False) -> bool:
98
+ """Whether the same address is worth a second attempt later.
99
+
100
+ Only temporary conditions qualify: 4xx greylisting and transport failures.
101
+ A 5xx or a 250 is final.
102
+ """
103
+ if transport_error:
104
+ return True
105
+ return is_greylist_code(code)
app/validator/smtp_client.py ADDED
@@ -0,0 +1,203 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Low-level SMTP client for mailbox probing (RFC 5321).
2
+
3
+ This is the core of the autonomous engine. Unlike a one-shot probe that opens a
4
+ TCP connection per address, `SmtpConnection` keeps a single session to a
5
+ receiving MX open and issues many `RCPT TO` probes over it (RSET between each).
6
+ Remote mail servers limit how often you may connect, and the TCP+TLS handshake
7
+ dominates cost — so connection reuse is what makes deep verification of a 10k
8
+ list feasible in minutes instead of hours.
9
+
10
+ No message is ever transmitted: the dialogue stops after RCPT and issues RSET,
11
+ so nothing can be delivered or marked as spam.
12
+
13
+ Every failure mode is returned as data (`RcptOutcome`), never raised, so one
14
+ dead host cannot abort a bulk job.
15
+ """
16
+ from __future__ import annotations
17
+
18
+ import socket
19
+ from dataclasses import dataclass, field
20
+ from typing import Callable, Optional
21
+
22
+ from .mx_intel import is_greylist_code, is_permanent_reject, parse_rcpt_code
23
+
24
+ CRLF = "\r\n"
25
+
26
+
27
+ @dataclass
28
+ class RcptOutcome:
29
+ """Result of one RCPT TO probe."""
30
+
31
+ code: Optional[int] = None
32
+ message: str = ""
33
+ transport_error: bool = False
34
+ error: Optional[str] = None
35
+
36
+ @property
37
+ def accepted(self) -> bool:
38
+ return self.code == 250
39
+
40
+ @property
41
+ def permanent_reject(self) -> bool:
42
+ return is_permanent_reject(self.code)
43
+
44
+ @property
45
+ def retryable(self) -> bool:
46
+ return self.transport_error or is_greylist_code(self.code)
47
+
48
+
49
+ def _default_connect(host: str, port: int, timeout: float):
50
+ sock = socket.create_connection((host, port), timeout=timeout)
51
+ sock.settimeout(timeout)
52
+ return sock
53
+
54
+
55
+ class SmtpConnection:
56
+ """A single reusable SMTP session against one receiving host."""
57
+
58
+ def __init__(
59
+ self,
60
+ host: str,
61
+ *,
62
+ port: int = 25,
63
+ timeout: float = 10.0,
64
+ helo_domain: str = "validator.local",
65
+ mail_from: str = "probe@validator.local",
66
+ connect: Optional[Callable[[str, int, float], object]] = None,
67
+ ):
68
+ self.host = host
69
+ self.port = port
70
+ self.timeout = timeout
71
+ self.helo_domain = helo_domain
72
+ self.mail_from = mail_from
73
+ self._connect = connect or _default_connect
74
+ self._sock = None
75
+ self.ready = False
76
+ self.server_code: Optional[int] = None
77
+ self.banner: str = ""
78
+ self._supports_pipelining = False
79
+
80
+ # ---- transport -------------------------------------------------
81
+ def open(self) -> bool:
82
+ """Connect + banner + EHLO. Returns True when the session is usable."""
83
+ try:
84
+ self._sock = self._connect(self.host, self.port, self.timeout)
85
+ except Exception as exc: # connection refused / blocked / DNS
86
+ self._sock = None
87
+ self.banner = f"connect failed: {exc}"
88
+ self.ready = False
89
+ return False
90
+ try:
91
+ code, text = self._read_response()
92
+ self.banner = text
93
+ if code != 220:
94
+ self.ready = False
95
+ return False
96
+ self._send(f"EHLO {self.helo_domain}")
97
+ code, text = self._read_response()
98
+ if code != 250:
99
+ # Fall back to HELO for ancient servers.
100
+ self._send(f"HELO {self.helo_domain}")
101
+ code, text = self._read_response()
102
+ if code != 250:
103
+ self.ready = False
104
+ return False
105
+ self._supports_pipelining = "PIPELINING" in text.upper()
106
+ self.server_code = code
107
+ self.ready = True
108
+ return True
109
+ except Exception as exc:
110
+ self.banner = f"handshake failed: {exc}"
111
+ self.ready = False
112
+ return False
113
+
114
+ def _send(self, line: str) -> None:
115
+ if self._sock is None:
116
+ raise OSError("socket closed")
117
+ self._sock.sendall((line + CRLF).encode("utf-8"))
118
+
119
+ def _read_response(self) -> tuple[Optional[int], str]:
120
+ """Read one (possibly multiline) SMTP response.
121
+
122
+ Multiline replies use `250-first`, `250-more`, `250 last` — the code is
123
+ repeated on every line and the final line has a space after the code.
124
+ Reading only one line would desynchronise the whole session.
125
+ """
126
+ if self._sock is None:
127
+ raise OSError("socket closed")
128
+ lines: list[str] = []
129
+ while True:
130
+ raw = self._sock.recv(4096)
131
+ if not raw:
132
+ raise OSError("connection closed by peer")
133
+ text = raw.decode("utf-8", "replace")
134
+ for line in text.split(CRLF):
135
+ if not line:
136
+ continue
137
+ lines.append(line)
138
+ # "250-last" continues, "250 last" or a short line ends.
139
+ if len(line) >= 4 and line[3] == "-":
140
+ continue
141
+ joined = "\n".join(lines)
142
+ return parse_rcpt_code(line), joined
143
+ # A chunk may end mid-line; keep reading.
144
+ if lines and len(lines[-1]) >= 4 and lines[-1][3] == " ":
145
+ joined = "\n".join(lines)
146
+ return parse_rcpt_code(lines[-1]), joined
147
+
148
+ # ---- probing ---------------------------------------------------
149
+ def probe(self, email: str) -> RcptOutcome:
150
+ """Ask the receiving server whether `email` is accepted."""
151
+ if not self.ready or self._sock is None:
152
+ return RcptOutcome(
153
+ transport_error=True, error="session not ready", retryable=True
154
+ )
155
+ try:
156
+ self._send(f"MAIL FROM:<{self.mail_from}>")
157
+ code, text = self._read_response()
158
+ if code is None or code >= 400:
159
+ return RcptOutcome(
160
+ code=code,
161
+ message=text,
162
+ transport_error=True,
163
+ error=f"MAIL FROM rejected: {text[:120]}",
164
+ )
165
+
166
+ self._send(f"RCPT TO:<{email}>")
167
+ code, text = self._read_response()
168
+
169
+ # Always reset so the next probe starts clean; never send DATA.
170
+ try:
171
+ self._send("RSET")
172
+ self._read_response()
173
+ except Exception:
174
+ pass
175
+
176
+ return RcptOutcome(code=code, message=text)
177
+ except Exception as exc:
178
+ return RcptOutcome(transport_error=True, error=str(exc))
179
+
180
+ def quit(self) -> None:
181
+ try:
182
+ if self._sock is not None:
183
+ self._send("QUIT")
184
+ except Exception:
185
+ pass
186
+ finally:
187
+ self.close()
188
+
189
+ def close(self) -> None:
190
+ if self._sock is not None:
191
+ try:
192
+ self._sock.close()
193
+ except Exception:
194
+ pass
195
+ self._sock = None
196
+ self.ready = False
197
+
198
+ def __enter__(self) -> "SmtpConnection":
199
+ self.open()
200
+ return self
201
+
202
+ def __exit__(self, *exc) -> None:
203
+ self.quit()
tests/test_autonomous_provider.py ADDED
@@ -0,0 +1,102 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import unittest
2
+ from unittest.mock import patch
3
+
4
+ from app.config import settings
5
+ from app.models import SMTPResult
6
+ from app.validator.mailbox_provider import (
7
+ AutonomousSmtpProvider,
8
+ LocalSmtpProvider,
9
+ MillionVerifierProvider,
10
+ resolve_provider,
11
+ )
12
+
13
+
14
+ class AutonomousProviderTests(unittest.IsolatedAsyncioTestCase):
15
+ """The engine must stand alone: direct SMTP is the default, and no
16
+ third-party key may be required for it to function."""
17
+
18
+ async def test_verify_uses_batch_engine(self):
19
+ captured = {}
20
+
21
+ class FakeBatch:
22
+ def verify_batch(self, pairs):
23
+ captured["pairs"] = list(pairs)
24
+ return {e: SMTPResult(verified=True, smtp_code=250) for e, _ in pairs}
25
+
26
+ p = AutonomousSmtpProvider(batch=FakeBatch())
27
+ out = await p.verify("a@corp.test", "mx.corp.test")
28
+ self.assertTrue(out.verified)
29
+ self.assertEqual(captured["pairs"], [("a@corp.test", "mx.corp.test")])
30
+
31
+ async def test_catch_all_probe_delegates_to_batch(self):
32
+ class FakeBatch:
33
+ def verify_batch(self, pairs):
34
+ # The gibberish probe is rejected -> not catch-all.
35
+ return {e: SMTPResult(verified=False, smtp_code=550) for e, _ in pairs}
36
+
37
+ p = AutonomousSmtpProvider(batch=FakeBatch())
38
+ is_ca, confidence = await p.catch_all("corp.test", "mx.corp.test")
39
+ self.assertIs(is_ca, False)
40
+ self.assertGreater(confidence, 0.5)
41
+
42
+ async def test_catch_all_unknown_on_transport_failure(self):
43
+ class FakeBatch:
44
+ def verify_batch(self, pairs):
45
+ return {e: SMTPResult(verified=None, error="transport_error") for e, _ in pairs}
46
+
47
+ p = AutonomousSmtpProvider(batch=FakeBatch())
48
+ is_ca, confidence = await p.catch_all("corp.test", "mx.corp.test")
49
+ self.assertIsNone(is_ca)
50
+ self.assertEqual(confidence, 0.0)
51
+
52
+ async def test_catch_all_true_when_gibberish_accepted(self):
53
+ class FakeBatch:
54
+ def verify_batch(self, pairs):
55
+ return {
56
+ e: SMTPResult(verified=None, error="catch_all: corp.test")
57
+ for e, _ in pairs
58
+ }
59
+
60
+ p = AutonomousSmtpProvider(batch=FakeBatch())
61
+ is_ca, confidence = await p.catch_all("corp.test", "mx.corp.test")
62
+ self.assertIs(is_ca, True)
63
+ self.assertGreater(confidence, 0.5)
64
+
65
+
66
+ class DefaultProviderTests(unittest.TestCase):
67
+ def test_auto_without_key_resolves_to_autonomous(self):
68
+ with patch.object(settings, "mailbox_provider", "auto"), patch.object(
69
+ settings, "mv_api_key", ""
70
+ ):
71
+ self.assertIsInstance(resolve_provider(), AutonomousSmtpProvider)
72
+
73
+ def test_local_forced_resolves_to_autonomous(self):
74
+ with patch.object(settings, "mailbox_provider", "local"):
75
+ self.assertIsInstance(resolve_provider(), AutonomousSmtpProvider)
76
+
77
+ def test_api_forced_still_available(self):
78
+ with patch.object(settings, "mailbox_provider", "api"), patch.object(
79
+ settings, "mv_api_key", "k"
80
+ ):
81
+ self.assertIsInstance(resolve_provider(), MillionVerifierProvider)
82
+
83
+ def test_auto_with_key_and_preference_uses_api(self):
84
+ with patch.object(settings, "mailbox_provider", "auto"), patch.object(
85
+ settings, "mv_api_key", "k"
86
+ ), patch.object(settings, "prefer_api_provider", True):
87
+ self.assertIsInstance(resolve_provider(), MillionVerifierProvider)
88
+
89
+ def test_auto_with_key_but_no_preference_stays_autonomous(self):
90
+ # Independence by default: a stray key must not silently re-route the
91
+ # engine through a third party.
92
+ with patch.object(settings, "mailbox_provider", "auto"), patch.object(
93
+ settings, "mv_api_key", "k"
94
+ ), patch.object(settings, "prefer_api_provider", False):
95
+ self.assertIsInstance(resolve_provider(), AutonomousSmtpProvider)
96
+
97
+ def test_legacy_local_provider_still_importable(self):
98
+ self.assertTrue(callable(LocalSmtpProvider))
99
+
100
+
101
+ if __name__ == "__main__":
102
+ unittest.main()
tests/test_engine_dns_failures.py CHANGED
@@ -78,7 +78,15 @@ class EngineDNSFailureTests(unittest.IsolatedAsyncioTestCase):
78
  mx_records=[{"host": "example.test", "priority": 0}],
79
  a_fallback=True,
80
  )
81
- engine = EmailValidationEngine()
 
 
 
 
 
 
 
 
82
  with (
83
  patch(
84
  "app.validator.engine.validate_syntax",
@@ -93,14 +101,6 @@ class EngineDNSFailureTests(unittest.IsolatedAsyncioTestCase):
93
  "app.validator.engine.check_dns", new=AsyncMock(return_value=dns_result)
94
  ),
95
  patch("app.validator.engine.check_disposable", return_value=None),
96
- patch(
97
- "app.validator.mailbox_provider.smtp_verifier.verify",
98
- new=AsyncMock(return_value=SMTPResult(verified=True)),
99
- ),
100
- patch(
101
- "app.validator.mailbox_provider.smtp_verifier.check_catch_all",
102
- new=AsyncMock(return_value=(False, 0.9)),
103
- ),
104
  ):
105
  result = await engine.validate("person@example.test", deep=True)
106
 
 
78
  mx_records=[{"host": "example.test", "priority": 0}],
79
  a_fallback=True,
80
  )
81
+
82
+ class FakeMailbox:
83
+ async def verify(self, email, mx_host):
84
+ return SMTPResult(verified=True)
85
+
86
+ async def catch_all(self, domain, mx_host):
87
+ return (False, 0.9)
88
+
89
+ engine = EmailValidationEngine(mailbox=FakeMailbox())
90
  with (
91
  patch(
92
  "app.validator.engine.validate_syntax",
 
101
  "app.validator.engine.check_dns", new=AsyncMock(return_value=dns_result)
102
  ),
103
  patch("app.validator.engine.check_disposable", return_value=None),
 
 
 
 
 
 
 
 
104
  ):
105
  result = await engine.validate("person@example.test", deep=True)
106
 
tests/test_engine_metadata.py CHANGED
@@ -41,34 +41,48 @@ def _disposable(**kw):
41
  return DisposableResult(**base)
42
 
43
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
44
  class EngineMetadataTests(unittest.IsolatedAsyncioTestCase):
45
  """The engine must emit the provenance fields the frontend contract expects:
46
  checks_run, reason_code, validator_version, run_id (RC5)."""
47
 
48
  async def test_deep_result_emits_provenance_fields(self):
49
- engine = EmailValidationEngine()
50
  with (
51
  patch("app.validator.engine.validate_syntax", return_value=_syntax()),
52
- patch(
53
- "app.validator.engine.check_dns",
54
- new=AsyncMock(return_value=_dns()),
55
- ),
56
- patch(
57
- "app.validator.engine.check_disposable",
58
- return_value=_disposable(),
59
- ),
60
- patch(
61
- "app.validator.mailbox_provider.smtp_verifier.verify",
62
- new=AsyncMock(return_value=SMTPResult(verified=True, smtp_code=250)),
63
- ),
64
- patch(
65
- "app.validator.mailbox_provider.smtp_verifier.check_catch_all",
66
- new=AsyncMock(return_value=(False, 0.9)),
67
- ),
68
  ):
69
  result = await engine.validate("person@example.test", deep=True)
70
 
71
- # Provenance: which layers ran, engine version, a correlation id.
72
  self.assertEqual(
73
  result.checks_run,
74
  ["syntax", "dns", "mx", "disposable", "catch_all", "smtp", "scoring"],
@@ -78,21 +92,14 @@ class EngineMetadataTests(unittest.IsolatedAsyncioTestCase):
78
  self.assertGreater(len(result.run_id), 5)
79
 
80
  async def test_fast_mode_checks_run_excludes_mailbox_layers(self):
81
- engine = EmailValidationEngine()
82
  with (
83
  patch("app.validator.engine.validate_syntax", return_value=_syntax()),
84
- patch(
85
- "app.validator.engine.check_dns",
86
- new=AsyncMock(return_value=_dns()),
87
- ),
88
- patch(
89
- "app.validator.engine.check_disposable",
90
- return_value=_disposable(),
91
- ),
92
  ):
93
  result = await engine.validate("person@example.test", deep=False)
94
 
95
- # deep=False never runs catch_all/smtp, so those layers must be absent.
96
  self.assertEqual(
97
  result.checks_run, ["syntax", "dns", "mx", "disposable", "scoring"]
98
  )
@@ -100,7 +107,7 @@ class EngineMetadataTests(unittest.IsolatedAsyncioTestCase):
100
  self.assertIsNone(result.catch_all)
101
 
102
  async def test_reason_code_dns_timeout(self):
103
- engine = EmailValidationEngine()
104
  with (
105
  patch("app.validator.engine.validate_syntax", return_value=_syntax()),
106
  patch(
@@ -120,7 +127,7 @@ class EngineMetadataTests(unittest.IsolatedAsyncioTestCase):
120
  self.assertEqual(result.reason_code, "dns_timeout")
121
 
122
  async def test_reason_code_nxdomain(self):
123
- engine = EmailValidationEngine()
124
  with (
125
  patch("app.validator.engine.validate_syntax", return_value=_syntax()),
126
  patch(
@@ -140,25 +147,13 @@ class EngineMetadataTests(unittest.IsolatedAsyncioTestCase):
140
  self.assertEqual(result.reason_code, "nxdomain")
141
 
142
  async def test_reason_code_catch_all(self):
143
- engine = EmailValidationEngine()
 
 
144
  with (
145
  patch("app.validator.engine.validate_syntax", return_value=_syntax()),
146
- patch(
147
- "app.validator.engine.check_dns",
148
- new=AsyncMock(return_value=_dns()),
149
- ),
150
- patch(
151
- "app.validator.engine.check_disposable",
152
- return_value=_disposable(),
153
- ),
154
- patch(
155
- "app.validator.mailbox_provider.smtp_verifier.verify",
156
- new=AsyncMock(return_value=SMTPResult(verified=True, smtp_code=250)),
157
- ),
158
- patch(
159
- "app.validator.mailbox_provider.smtp_verifier.check_catch_all",
160
- new=AsyncMock(return_value=(True, 0.95)),
161
- ),
162
  ):
163
  result = await engine.validate("person@example.test", deep=True)
164
 
@@ -167,33 +162,19 @@ class EngineMetadataTests(unittest.IsolatedAsyncioTestCase):
167
 
168
  async def test_explicit_5xx_rejection_outranks_catch_all(self):
169
  # A definitive "mailbox does not exist" (5xx) is stronger and more
170
- # actionable than the domain-level catch-all flag: reporting catch_all
171
- # beside status=invalid is incoherent. The explicit rejection must win.
172
- engine = EmailValidationEngine()
 
 
 
 
 
 
173
  with (
174
  patch("app.validator.engine.validate_syntax", return_value=_syntax()),
175
- patch(
176
- "app.validator.engine.check_dns",
177
- new=AsyncMock(return_value=_dns()),
178
- ),
179
- patch(
180
- "app.validator.engine.check_disposable",
181
- return_value=_disposable(),
182
- ),
183
- patch(
184
- "app.validator.mailbox_provider.smtp_verifier.verify",
185
- new=AsyncMock(
186
- return_value=SMTPResult(
187
- verified=False,
188
- smtp_code=550,
189
- smtp_message="550 mailbox does not exist (provider confirmed)",
190
- )
191
- ),
192
- ),
193
- patch(
194
- "app.validator.mailbox_provider.smtp_verifier.check_catch_all",
195
- new=AsyncMock(return_value=(True, 0.95)),
196
- ),
197
  ):
198
  result = await engine.validate("person@example.test", deep=True)
199
 
@@ -202,27 +183,14 @@ class EngineMetadataTests(unittest.IsolatedAsyncioTestCase):
202
  self.assertEqual(result.status, ValidationStatus.INVALID)
203
 
204
  async def test_reason_code_smtp_timeout(self):
205
- engine = EmailValidationEngine()
 
 
 
206
  with (
207
  patch("app.validator.engine.validate_syntax", return_value=_syntax()),
208
- patch(
209
- "app.validator.engine.check_dns",
210
- new=AsyncMock(return_value=_dns()),
211
- ),
212
- patch(
213
- "app.validator.engine.check_disposable",
214
- return_value=_disposable(),
215
- ),
216
- patch(
217
- "app.validator.mailbox_provider.smtp_verifier.verify",
218
- new=AsyncMock(
219
- return_value=SMTPResult(verified=None, error="SMTP verification timed out")
220
- ),
221
- ),
222
- patch(
223
- "app.validator.mailbox_provider.smtp_verifier.check_catch_all",
224
- new=AsyncMock(return_value=(None, 0.0)),
225
- ),
226
  ):
227
  result = await engine.validate("person@example.test", deep=True)
228
 
@@ -234,28 +202,14 @@ class CatchAllUnknownTests(unittest.IsolatedAsyncioTestCase):
234
  False ("domain rejects unknown recipients"). RC6."""
235
 
236
  async def test_catch_all_probe_unavailable_is_unknown_not_false(self):
237
- engine = EmailValidationEngine()
 
 
 
238
  with (
239
  patch("app.validator.engine.validate_syntax", return_value=_syntax()),
240
- patch(
241
- "app.validator.engine.check_dns",
242
- new=AsyncMock(return_value=_dns()),
243
- ),
244
- patch(
245
- "app.validator.engine.check_disposable",
246
- return_value=_disposable(),
247
- ),
248
- patch(
249
- "app.validator.mailbox_provider.smtp_verifier.verify",
250
- new=AsyncMock(
251
- return_value=SMTPResult(verified=None, error="SMTP verification timed out")
252
- ),
253
- ),
254
- # Probe returned "unknown" (None, 0.0) — the blocked-host case.
255
- patch(
256
- "app.validator.mailbox_provider.smtp_verifier.check_catch_all",
257
- new=AsyncMock(return_value=(None, 0.0)),
258
- ),
259
  ):
260
  result = await engine.validate("person@example.test", deep=True)
261
 
@@ -263,25 +217,13 @@ class CatchAllUnknownTests(unittest.IsolatedAsyncioTestCase):
263
  self.assertEqual(result.catch_all.confidence, 0.0)
264
 
265
  async def test_catch_all_exception_is_unknown_not_false(self):
266
- engine = EmailValidationEngine()
 
 
267
  with (
268
  patch("app.validator.engine.validate_syntax", return_value=_syntax()),
269
- patch(
270
- "app.validator.engine.check_dns",
271
- new=AsyncMock(return_value=_dns()),
272
- ),
273
- patch(
274
- "app.validator.engine.check_disposable",
275
- return_value=_disposable(),
276
- ),
277
- patch(
278
- "app.validator.mailbox_provider.smtp_verifier.verify",
279
- new=AsyncMock(return_value=SMTPResult(verified=True, smtp_code=250)),
280
- ),
281
- patch(
282
- "app.validator.mailbox_provider.smtp_verifier.check_catch_all",
283
- new=AsyncMock(side_effect=RuntimeError("port 25 unreachable")),
284
- ),
285
  ):
286
  result = await engine.validate("person@example.test", deep=True)
287
 
@@ -289,66 +231,41 @@ class CatchAllUnknownTests(unittest.IsolatedAsyncioTestCase):
289
 
290
 
291
  class ScoreCoherenceTests(unittest.IsolatedAsyncioTestCase):
292
- """A perfect score (100/low) must only appear when a mailbox verdict exists.
293
- Unverified-but-plausible rows are capped and marked medium. RC4."""
294
 
295
  async def test_smtp_verified_can_reach_high_score(self):
296
- engine = EmailValidationEngine()
 
 
297
  with (
298
  patch("app.validator.engine.validate_syntax", return_value=_syntax()),
299
- patch(
300
- "app.validator.engine.check_dns",
301
- new=AsyncMock(return_value=_dns()),
302
- ),
303
  patch(
304
  "app.validator.engine.check_disposable",
305
  return_value=_disposable(is_free_provider=False),
306
  ),
307
- patch(
308
- "app.validator.mailbox_provider.smtp_verifier.verify",
309
- new=AsyncMock(return_value=SMTPResult(verified=True, smtp_code=250)),
310
- ),
311
- patch(
312
- "app.validator.mailbox_provider.smtp_verifier.check_catch_all",
313
- new=AsyncMock(return_value=(False, 0.9)),
314
- ),
315
  ):
316
  result = await engine.validate("person@example.test", deep=True)
317
 
318
- # Definitive mailbox acceptance + clean domain → low risk, high score.
319
  self.assertGreaterEqual(result.scoring.score, 75)
320
  self.assertEqual(result.scoring.risk_level.value, "low")
321
  self.assertEqual(result.status, ValidationStatus.VALID)
322
 
323
  async def test_unverified_mailbox_never_scores_100(self):
324
- engine = EmailValidationEngine()
 
 
 
325
  with (
326
  patch("app.validator.engine.validate_syntax", return_value=_syntax()),
327
- patch(
328
- "app.validator.engine.check_dns",
329
- new=AsyncMock(return_value=_dns()),
330
- ),
331
- patch(
332
- "app.validator.engine.check_disposable",
333
- return_value=_disposable(),
334
- ),
335
- patch(
336
- "app.validator.mailbox_provider.smtp_verifier.verify",
337
- new=AsyncMock(
338
- return_value=SMTPResult(verified=None, error="SMTP verification timed out")
339
- ),
340
- ),
341
- patch(
342
- "app.validator.mailbox_provider.smtp_verifier.check_catch_all",
343
- new=AsyncMock(return_value=(None, 0.0)),
344
- ),
345
  ):
346
  result = await engine.validate("person@example.test", deep=True)
347
 
348
- # Inconclusive SMTP caps the score below "low risk" territory.
349
  self.assertLess(result.scoring.score, 75)
350
  self.assertNotEqual(result.scoring.risk_level.value, "low")
351
 
352
 
353
  if __name__ == "__main__":
354
- unittest.main()
 
41
  return DisposableResult(**base)
42
 
43
 
44
+ class FakeMailbox:
45
+ """Injectable mailbox provider — controls the Layer 5/6 verdicts exactly.
46
+
47
+ Injecting the provider (instead of patching module internals) keeps these
48
+ tests independent of which concrete provider the engine resolves by default.
49
+ """
50
+
51
+ def __init__(self, smtp=None, catch_all=(False, 0.9), raises=None):
52
+ self._smtp = smtp if smtp is not None else SMTPResult(verified=True, smtp_code=250)
53
+ self._catch_all = catch_all
54
+ self._raises = raises
55
+
56
+ async def verify(self, email, mx_host):
57
+ if self._raises:
58
+ raise self._raises
59
+ return self._smtp
60
+
61
+ async def catch_all(self, domain, mx_host):
62
+ if self._raises:
63
+ raise self._raises
64
+ return self._catch_all
65
+
66
+
67
+ def _engine_with(smtp=None, catch_all=(False, 0.9)):
68
+ return EmailValidationEngine(
69
+ mailbox=FakeMailbox(smtp=smtp, catch_all=catch_all)
70
+ )
71
+
72
+
73
  class EngineMetadataTests(unittest.IsolatedAsyncioTestCase):
74
  """The engine must emit the provenance fields the frontend contract expects:
75
  checks_run, reason_code, validator_version, run_id (RC5)."""
76
 
77
  async def test_deep_result_emits_provenance_fields(self):
78
+ engine = _engine_with()
79
  with (
80
  patch("app.validator.engine.validate_syntax", return_value=_syntax()),
81
+ patch("app.validator.engine.check_dns", new=AsyncMock(return_value=_dns())),
82
+ patch("app.validator.engine.check_disposable", return_value=_disposable()),
 
 
 
 
 
 
 
 
 
 
 
 
 
 
83
  ):
84
  result = await engine.validate("person@example.test", deep=True)
85
 
 
86
  self.assertEqual(
87
  result.checks_run,
88
  ["syntax", "dns", "mx", "disposable", "catch_all", "smtp", "scoring"],
 
92
  self.assertGreater(len(result.run_id), 5)
93
 
94
  async def test_fast_mode_checks_run_excludes_mailbox_layers(self):
95
+ engine = _engine_with()
96
  with (
97
  patch("app.validator.engine.validate_syntax", return_value=_syntax()),
98
+ patch("app.validator.engine.check_dns", new=AsyncMock(return_value=_dns())),
99
+ patch("app.validator.engine.check_disposable", return_value=_disposable()),
 
 
 
 
 
 
100
  ):
101
  result = await engine.validate("person@example.test", deep=False)
102
 
 
103
  self.assertEqual(
104
  result.checks_run, ["syntax", "dns", "mx", "disposable", "scoring"]
105
  )
 
107
  self.assertIsNone(result.catch_all)
108
 
109
  async def test_reason_code_dns_timeout(self):
110
+ engine = _engine_with()
111
  with (
112
  patch("app.validator.engine.validate_syntax", return_value=_syntax()),
113
  patch(
 
127
  self.assertEqual(result.reason_code, "dns_timeout")
128
 
129
  async def test_reason_code_nxdomain(self):
130
+ engine = _engine_with()
131
  with (
132
  patch("app.validator.engine.validate_syntax", return_value=_syntax()),
133
  patch(
 
147
  self.assertEqual(result.reason_code, "nxdomain")
148
 
149
  async def test_reason_code_catch_all(self):
150
+ engine = _engine_with(
151
+ smtp=SMTPResult(verified=True, smtp_code=250), catch_all=(True, 0.95)
152
+ )
153
  with (
154
  patch("app.validator.engine.validate_syntax", return_value=_syntax()),
155
+ patch("app.validator.engine.check_dns", new=AsyncMock(return_value=_dns())),
156
+ patch("app.validator.engine.check_disposable", return_value=_disposable()),
 
 
 
 
 
 
 
 
 
 
 
 
 
 
157
  ):
158
  result = await engine.validate("person@example.test", deep=True)
159
 
 
162
 
163
  async def test_explicit_5xx_rejection_outranks_catch_all(self):
164
  # A definitive "mailbox does not exist" (5xx) is stronger and more
165
+ # actionable than the domain-level catch-all flag.
166
+ engine = _engine_with(
167
+ smtp=SMTPResult(
168
+ verified=False,
169
+ smtp_code=550,
170
+ smtp_message="550 mailbox does not exist (provider confirmed)",
171
+ ),
172
+ catch_all=(True, 0.95),
173
+ )
174
  with (
175
  patch("app.validator.engine.validate_syntax", return_value=_syntax()),
176
+ patch("app.validator.engine.check_dns", new=AsyncMock(return_value=_dns())),
177
+ patch("app.validator.engine.check_disposable", return_value=_disposable()),
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
178
  ):
179
  result = await engine.validate("person@example.test", deep=True)
180
 
 
183
  self.assertEqual(result.status, ValidationStatus.INVALID)
184
 
185
  async def test_reason_code_smtp_timeout(self):
186
+ engine = _engine_with(
187
+ smtp=SMTPResult(verified=None, error="SMTP verification timed out"),
188
+ catch_all=(None, 0.0),
189
+ )
190
  with (
191
  patch("app.validator.engine.validate_syntax", return_value=_syntax()),
192
+ patch("app.validator.engine.check_dns", new=AsyncMock(return_value=_dns())),
193
+ patch("app.validator.engine.check_disposable", return_value=_disposable()),
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
194
  ):
195
  result = await engine.validate("person@example.test", deep=True)
196
 
 
202
  False ("domain rejects unknown recipients"). RC6."""
203
 
204
  async def test_catch_all_probe_unavailable_is_unknown_not_false(self):
205
+ engine = _engine_with(
206
+ smtp=SMTPResult(verified=None, error="SMTP verification timed out"),
207
+ catch_all=(None, 0.0),
208
+ )
209
  with (
210
  patch("app.validator.engine.validate_syntax", return_value=_syntax()),
211
+ patch("app.validator.engine.check_dns", new=AsyncMock(return_value=_dns())),
212
+ patch("app.validator.engine.check_disposable", return_value=_disposable()),
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
213
  ):
214
  result = await engine.validate("person@example.test", deep=True)
215
 
 
217
  self.assertEqual(result.catch_all.confidence, 0.0)
218
 
219
  async def test_catch_all_exception_is_unknown_not_false(self):
220
+ engine = EmailValidationEngine(
221
+ mailbox=FakeMailbox(raises=RuntimeError("port 25 unreachable"))
222
+ )
223
  with (
224
  patch("app.validator.engine.validate_syntax", return_value=_syntax()),
225
+ patch("app.validator.engine.check_dns", new=AsyncMock(return_value=_dns())),
226
+ patch("app.validator.engine.check_disposable", return_value=_disposable()),
 
 
 
 
 
 
 
 
 
 
 
 
 
 
227
  ):
228
  result = await engine.validate("person@example.test", deep=True)
229
 
 
231
 
232
 
233
  class ScoreCoherenceTests(unittest.IsolatedAsyncioTestCase):
234
+ """A perfect score (100/low) must only appear when a mailbox verdict exists."""
 
235
 
236
  async def test_smtp_verified_can_reach_high_score(self):
237
+ engine = _engine_with(
238
+ smtp=SMTPResult(verified=True, smtp_code=250), catch_all=(False, 0.9)
239
+ )
240
  with (
241
  patch("app.validator.engine.validate_syntax", return_value=_syntax()),
242
+ patch("app.validator.engine.check_dns", new=AsyncMock(return_value=_dns())),
 
 
 
243
  patch(
244
  "app.validator.engine.check_disposable",
245
  return_value=_disposable(is_free_provider=False),
246
  ),
 
 
 
 
 
 
 
 
247
  ):
248
  result = await engine.validate("person@example.test", deep=True)
249
 
 
250
  self.assertGreaterEqual(result.scoring.score, 75)
251
  self.assertEqual(result.scoring.risk_level.value, "low")
252
  self.assertEqual(result.status, ValidationStatus.VALID)
253
 
254
  async def test_unverified_mailbox_never_scores_100(self):
255
+ engine = _engine_with(
256
+ smtp=SMTPResult(verified=None, error="SMTP verification timed out"),
257
+ catch_all=(None, 0.0),
258
+ )
259
  with (
260
  patch("app.validator.engine.validate_syntax", return_value=_syntax()),
261
+ patch("app.validator.engine.check_dns", new=AsyncMock(return_value=_dns())),
262
+ patch("app.validator.engine.check_disposable", return_value=_disposable()),
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
263
  ):
264
  result = await engine.validate("person@example.test", deep=True)
265
 
 
266
  self.assertLess(result.scoring.score, 75)
267
  self.assertNotEqual(result.scoring.risk_level.value, "low")
268
 
269
 
270
  if __name__ == "__main__":
271
+ unittest.main()
tests/test_mailbox_provider.py CHANGED
@@ -7,6 +7,7 @@ from app.validator.mailbox_provider import (
7
  MailboxProvider,
8
  MillionVerifierProvider,
9
  LocalSmtpProvider,
 
10
  resolve_provider,
11
  map_mv_result,
12
  )
@@ -133,21 +134,21 @@ class ResolveProviderTests(unittest.TestCase):
133
  ):
134
  self.assertIsInstance(resolve_provider(), MillionVerifierProvider)
135
 
136
- def test_local_forced(self):
137
  with patch.object(settings, "mailbox_provider", "local"):
138
- self.assertIsInstance(resolve_provider(), LocalSmtpProvider)
139
 
140
- def test_auto_with_key_uses_api(self):
141
  with patch.object(settings, "mailbox_provider", "auto"), patch.object(
142
  settings, "mv_api_key", "k"
143
- ):
144
  self.assertIsInstance(resolve_provider(), MillionVerifierProvider)
145
 
146
- def test_auto_without_key_uses_local(self):
147
  with patch.object(settings, "mailbox_provider", "auto"), patch.object(
148
  settings, "mv_api_key", ""
149
  ):
150
- self.assertIsInstance(resolve_provider(), LocalSmtpProvider)
151
 
152
  def test_provider_satisfies_protocol(self):
153
  # Structural check: both providers expose verify + catch_all.
 
7
  MailboxProvider,
8
  MillionVerifierProvider,
9
  LocalSmtpProvider,
10
+ AutonomousSmtpProvider,
11
  resolve_provider,
12
  map_mv_result,
13
  )
 
134
  ):
135
  self.assertIsInstance(resolve_provider(), MillionVerifierProvider)
136
 
137
+ def test_local_forced_is_autonomous(self):
138
  with patch.object(settings, "mailbox_provider", "local"):
139
+ self.assertIsInstance(resolve_provider(), AutonomousSmtpProvider)
140
 
141
+ def test_auto_with_key_prefers_api_only_when_opted_in(self):
142
  with patch.object(settings, "mailbox_provider", "auto"), patch.object(
143
  settings, "mv_api_key", "k"
144
+ ), patch.object(settings, "prefer_api_provider", True):
145
  self.assertIsInstance(resolve_provider(), MillionVerifierProvider)
146
 
147
+ def test_auto_without_key_is_autonomous(self):
148
  with patch.object(settings, "mailbox_provider", "auto"), patch.object(
149
  settings, "mv_api_key", ""
150
  ):
151
+ self.assertIsInstance(resolve_provider(), AutonomousSmtpProvider)
152
 
153
  def test_provider_satisfies_protocol(self):
154
  # Structural check: both providers expose verify + catch_all.
tests/test_mx_batch.py ADDED
@@ -0,0 +1,149 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import unittest
2
+
3
+ from app.validator.mx_batch import CatchAllCache, MxBatchVerifier
4
+ from app.validator.smtp_client import RcptOutcome
5
+
6
+
7
+ class FakeConnection:
8
+ """Records probes and answers from a scripted map.
9
+
10
+ Keyed by lowercased address; a "*" entry is the default answer, which is how
11
+ a catch-all domain behaves (accepts everything).
12
+ """
13
+
14
+ registry: dict[str, dict] = {}
15
+ opened: list[str] = []
16
+ closed: list[int] = []
17
+
18
+ def __init__(self, host, **kwargs):
19
+ self.host = host
20
+ self.answers = FakeConnection.registry.get(host, {})
21
+ self.ready = True
22
+ self.opened.append(host)
23
+
24
+ def open(self):
25
+ self.ready = True
26
+ return True
27
+
28
+ def probe(self, email):
29
+ # Catch-all probe uses a gibberish local part -> "*" rule applies.
30
+ answer = self.answers.get(email.lower(), self.answers.get("*"))
31
+ if answer is None:
32
+ return RcptOutcome(code=550, message="550 5.1.1 no such user")
33
+ if isinstance(answer, RcptOutcome):
34
+ return answer
35
+ return RcptOutcome(code=answer, message=f"{answer} response")
36
+
37
+ def quit(self):
38
+ FakeConnection.closed.append(1)
39
+
40
+ def close(self):
41
+ pass
42
+
43
+
44
+ class MxBatchVerifierTests(unittest.TestCase):
45
+ def setUp(self):
46
+ FakeConnection.registry = {}
47
+ FakeConnection.opened = []
48
+ FakeConnection.closed = []
49
+
50
+ def verifier(self, **kw):
51
+ return MxBatchVerifier(
52
+ connection_factory=FakeConnection,
53
+ max_connections_per_host=kw.pop("max_connections_per_host", 2),
54
+ **kw,
55
+ )
56
+
57
+ def test_groups_by_mx_and_opens_one_session_per_host(self):
58
+ # google host: two addresses; corp host: one address
59
+ FakeConnection.registry = {
60
+ "gmail-smtp-in.l.google.com": {"a@gmail.com": 250, "b@gmail.com": 550, "*": 550},
61
+ "mx.corp.test": {"c@corp.test": 250, "*": 550},
62
+ }
63
+ v = self.verifier()
64
+ out = v.verify_batch(
65
+ [
66
+ ("a@gmail.com", "gmail-smtp-in.l.google.com"),
67
+ ("b@gmail.com", "gmail-smtp-in.l.google.com"),
68
+ ("c@corp.test", "mx.corp.test"),
69
+ ]
70
+ )
71
+ self.assertEqual(out["a@gmail.com"].verified, True)
72
+ self.assertEqual(out["b@gmail.com"].verified, False)
73
+ self.assertEqual(out["c@corp.test"].verified, True)
74
+ # One connection opened per MX host (not per address).
75
+ self.assertEqual(sorted(FakeConnection.opened), ["gmail-smtp-in.l.google.com", "mx.corp.test"])
76
+
77
+ def test_catch_all_domain_does_not_certify_mailbox(self):
78
+ # Microsoft 365 behaviour: accepts everything at RCPT.
79
+ FakeConnection.registry = {
80
+ "x.mail.protection.outlook.com": {"*": 250},
81
+ }
82
+ v = self.verifier()
83
+ out = v.verify_batch([("anyone@contoso.com", "x.mail.protection.outlook.com")])
84
+ result = out["anyone@contoso.com"]
85
+ # Accepted by an accept-all host, so NOT verified.
86
+ self.assertIsNone(result.verified)
87
+ self.assertIn("catch_all", (result.error or "").lower())
88
+
89
+ def test_catch_all_probe_is_cached_per_domain(self):
90
+ FakeConnection.registry = {"mx.corp.test": {"*": 250}}
91
+ v = self.verifier()
92
+ v.verify_batch([("a@corp.test", "mx.corp.test")])
93
+ probes_after_first = len(FakeConnection.opened)
94
+ # Second address in the same domain must reuse the cached catch-all flag.
95
+ v.verify_batch([("b@corp.test", "mx.corp.test")])
96
+ self.assertEqual(len(FakeConnection.opened), probes_after_first)
97
+
98
+ def test_transport_error_marks_unknown_not_invalid(self):
99
+ class DeadConn(FakeConnection):
100
+ def open(self):
101
+ self.ready = False
102
+ return False
103
+
104
+ FakeConnection.registry = {"mx.dead.test": {"*": 250}}
105
+ v = MxBatchVerifier(connection_factory=DeadConn)
106
+ out = v.verify_batch([("a@dead.test", "mx.dead.test")])
107
+ r = out["a@dead.test"]
108
+ self.assertIsNone(r.verified)
109
+ self.assertIsNotNone(r.error)
110
+
111
+ def test_greylisted_address_is_reported_retryable(self):
112
+ FakeConnection.registry = {
113
+ "mx.corp.test": {"a@corp.test": RcptOutcome(code=451, message="451 greylisted"), "*": 550}
114
+ }
115
+ v = self.verifier()
116
+ out = v.verify_batch([("a@corp.test", "mx.corp.test")])
117
+ self.assertIsNone(out["a@corp.test"].verified)
118
+
119
+ def test_empty_batch_returns_empty(self):
120
+ v = self.verifier()
121
+ self.assertEqual(v.verify_batch([]), {})
122
+
123
+
124
+ class CatchAllCacheTests(unittest.TestCase):
125
+ def test_stores_and_returns_within_ttl(self):
126
+ c = CatchAllCache(ttl_seconds=60)
127
+ c.put("corp.test", True)
128
+ self.assertIs(c.get("corp.test"), True)
129
+
130
+ def test_expires_after_ttl(self):
131
+ c = CatchAllCache(ttl_seconds=0)
132
+ c.put("corp.test", True)
133
+ self.assertIsNone(c.get("corp.test"))
134
+
135
+ def test_unknown_is_not_cached_as_false(self):
136
+ c = CatchAllCache(ttl_seconds=60)
137
+ c.put("corp.test", None)
138
+ # None (probe failed) must not be cached as a decision.
139
+ self.assertIsNone(c.get("corp.test"))
140
+
141
+ def test_distinguishes_false_from_missing(self):
142
+ c = CatchAllCache(ttl_seconds=60)
143
+ c.put("strict.test", False)
144
+ self.assertIs(c.get("strict.test"), False)
145
+ self.assertIsNone(c.get("never-seen.test"))
146
+
147
+
148
+ if __name__ == "__main__":
149
+ unittest.main()
tests/test_mx_intel.py ADDED
@@ -0,0 +1,109 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import unittest
2
+
3
+ from app.validator.mx_intel import (
4
+ MxPolicy,
5
+ classify_mx,
6
+ parse_rcpt_code,
7
+ is_greylist_code,
8
+ is_permanent_reject,
9
+ should_retry,
10
+ )
11
+
12
+
13
+ class ClassifyMxTests(unittest.TestCase):
14
+ """Recognising the receiving provider from its MX host lets the engine
15
+ apply the right policy: Google rejects unknown mailboxes at RCPT (trust it),
16
+ Microsoft 365 accepts everything and bounces later (never trust a 250)."""
17
+
18
+ def test_google_mx_is_strict(self):
19
+ for host in (
20
+ "gmail-smtp-in.l.google.com",
21
+ "alt1.aspmx.l.google.com",
22
+ "aspmx.l.google.com",
23
+ ):
24
+ p = classify_mx(host)
25
+ self.assertEqual(p.provider, "google", host)
26
+ self.assertTrue(p.trusts_rcpt, host)
27
+ self.assertFalse(p.accepts_all, host)
28
+
29
+ def test_microsoft365_is_accept_all(self):
30
+ for host in (
31
+ "example-com.mail.protection.outlook.com",
32
+ "mail.protection.outlook.com",
33
+ ):
34
+ p = classify_mx(host)
35
+ self.assertEqual(p.provider, "microsoft365", host)
36
+ self.assertTrue(p.accepts_all, host)
37
+ self.assertFalse(p.trusts_rcpt, host)
38
+
39
+ def test_mimecast_and_proofpoint_are_accept_all_gateways(self):
40
+ for host in (
41
+ "us-smtp-inbound-1.mimecast.com",
42
+ "mx0a-001b2d01.pphosted.com",
43
+ ):
44
+ p = classify_mx(host)
45
+ self.assertTrue(p.accepts_all, host)
46
+ self.assertFalse(p.trusts_rcpt, host)
47
+
48
+ def test_yahoo_is_strict(self):
49
+ p = classify_mx("mta5.am0.yahoodns.net")
50
+ self.assertEqual(p.provider, "yahoo")
51
+ self.assertTrue(p.trusts_rcpt)
52
+
53
+ def test_unknown_host_defaults_to_neutral(self):
54
+ p = classify_mx("mx.example-corp.test")
55
+ self.assertEqual(p.provider, "unknown")
56
+ self.assertFalse(p.accepts_all)
57
+ # Unknown providers are not assumed untrustworthy, but a 250 alone does
58
+ # not prove the mailbox exists — the catch-all probe decides that.
59
+ self.assertFalse(p.trusts_rcpt)
60
+
61
+ def test_case_and_trailing_dot_insensitive(self):
62
+ self.assertEqual(classify_mx("ASPMX.L.GOOGLE.COM.").provider, "google")
63
+
64
+
65
+ class RcptCodeTests(unittest.TestCase):
66
+ def test_250_is_accept(self):
67
+ self.assertEqual(parse_rcpt_code("250 2.1.5 Ok"), 250)
68
+
69
+ def test_550_is_reject(self):
70
+ self.assertEqual(parse_rcpt_code("550 5.1.1 The email account does not exist"), 550)
71
+
72
+ def test_non_numeric_returns_none(self):
73
+ self.assertIsNone(parse_rcpt_code("garbage"))
74
+
75
+ def test_4xx_is_greylist(self):
76
+ self.assertTrue(is_greylist_code(421))
77
+ self.assertTrue(is_greylist_code(450))
78
+ self.assertTrue(is_greylist_code(451))
79
+ self.assertFalse(is_greylist_code(250))
80
+ self.assertFalse(is_greylist_code(550))
81
+
82
+ def test_5xx_is_permanent(self):
83
+ self.assertTrue(is_permanent_reject(550))
84
+ self.assertTrue(is_permanent_reject(551))
85
+ self.assertFalse(is_permanent_reject(450))
86
+ self.assertFalse(is_permanent_reject(None))
87
+
88
+ def test_retry_policy_only_for_greylist(self):
89
+ self.assertTrue(should_retry(450))
90
+ self.assertTrue(should_retry(451))
91
+ self.assertFalse(should_retry(550))
92
+ self.assertFalse(should_retry(250))
93
+ self.assertFalse(should_retry(None))
94
+
95
+ def test_connection_error_retries(self):
96
+ # A transport failure is transient and worth one retry.
97
+ self.assertTrue(should_retry(None, transport_error=True))
98
+
99
+
100
+ class MxPolicyTests(unittest.TestCase):
101
+ def test_policy_is_immutable_and_descriptive(self):
102
+ p = MxPolicy(provider="google", trusts_rcpt=True, accepts_all=False)
103
+ self.assertEqual(p.provider, "google")
104
+ with self.assertRaises(Exception):
105
+ p.provider = "other" # type: ignore[misc]
106
+
107
+
108
+ if __name__ == "__main__":
109
+ unittest.main()
tests/test_smtp_client.py ADDED
@@ -0,0 +1,152 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import unittest
2
+
3
+ from app.validator.smtp_client import SmtpConnection, RcptOutcome
4
+
5
+
6
+ class FakeSock:
7
+ """Scripted TCP socket: returns queued byte chunks on recv, records sends."""
8
+
9
+ def __init__(self, chunks):
10
+ self.chunks = list(chunks)
11
+ self.sent: list[str] = []
12
+ self.closed = False
13
+ self.timeout = None
14
+
15
+ def settimeout(self, t):
16
+ self.timeout = t
17
+
18
+ def sendall(self, data: bytes):
19
+ self.sent.append(data.decode("utf-8", "replace"))
20
+
21
+ def recv(self, _n: int) -> bytes:
22
+ return self.chunks.pop(0) if self.chunks else b""
23
+
24
+ def close(self):
25
+ self.closed = True
26
+
27
+
28
+ def make_conn(chunks, **kw):
29
+ sock = FakeSock(chunks)
30
+ conn = SmtpConnection(
31
+ "mx.example.test",
32
+ timeout=5,
33
+ helo_domain="validator.test",
34
+ connect=lambda *a, **k: sock,
35
+ **kw,
36
+ )
37
+ return conn, sock
38
+
39
+
40
+ BANNER = b"220 mx.example.test ESMTP ready\r\n"
41
+ EHLO_OK = b"250-mx.example.test\r\n250-PIPELINING\r\n250 OK\r\n"
42
+
43
+
44
+ class SmtpConnectionTests(unittest.TestCase):
45
+ def test_handshake_reads_banner_and_sends_ehlo(self):
46
+ conn, sock = make_conn([BANNER, EHLO_OK, b"250 OK\r\n"])
47
+ conn.open()
48
+ self.assertTrue(conn.ready)
49
+ self.assertTrue(any(c.startswith("EHLO ") for c in sock.sent))
50
+ self.assertIn("validator.test", "".join(sock.sent))
51
+
52
+ def test_multiline_ehlo_is_parsed_as_single_response(self):
53
+ conn, _ = make_conn([BANNER, EHLO_OK])
54
+ conn.open()
55
+ self.assertEqual(conn.server_code, 250)
56
+
57
+ def test_accepting_rcpt_returns_250(self):
58
+ conn, sock = make_conn(
59
+ [BANNER, EHLO_OK, b"250 OK\r\n", b"250 2.1.5 Ok\r\n", b"250 OK\r\n"]
60
+ )
61
+ conn.open()
62
+ out = conn.probe("real@example.test")
63
+ self.assertEqual(out.code, 250)
64
+ self.assertTrue(out.accepted)
65
+ self.assertFalse(out.transport_error)
66
+ self.assertTrue(any(c.startswith("RCPT TO:") for c in sock.sent))
67
+
68
+ def test_rejecting_rcpt_returns_550(self):
69
+ conn, _ = make_conn(
70
+ [
71
+ BANNER,
72
+ EHLO_OK,
73
+ b"250 OK\r\n",
74
+ b"550 5.1.1 The email account that you tried to reach does not exist\r\n",
75
+ b"250 OK\r\n",
76
+ ]
77
+ )
78
+ conn.open()
79
+ out = conn.probe("ghost@example.test")
80
+ self.assertEqual(out.code, 550)
81
+ self.assertFalse(out.accepted)
82
+ self.assertIn("does not exist", out.message)
83
+
84
+ def test_multiple_probes_reuse_one_connection(self):
85
+ # The whole point of the engine: one TCP session, many RCPT probes.
86
+ conn, sock = make_conn(
87
+ [
88
+ BANNER,
89
+ EHLO_OK,
90
+ b"250 OK\r\n", # MAIL FROM #1
91
+ b"250 OK\r\n", # RCPT #1
92
+ b"250 OK\r\n", # RSET
93
+ b"250 OK\r\n", # MAIL FROM #2
94
+ b"550 5.1.1 nope\r\n", # RCPT #2
95
+ b"250 OK\r\n", # RSET
96
+ b"221 Bye\r\n",
97
+ ]
98
+ )
99
+ conn.open()
100
+ first = conn.probe("a@example.test")
101
+ second = conn.probe("b@example.test")
102
+ conn.quit()
103
+
104
+ self.assertTrue(first.accepted)
105
+ self.assertFalse(second.accepted)
106
+ # Two MAIL FROM commands, one EHLO, one connection.
107
+ sends = "".join(sock.sent)
108
+ self.assertEqual(sends.count("MAIL FROM:"), 2)
109
+ self.assertEqual(sends.count("EHLO "), 1)
110
+ self.assertEqual(sends.count("RSET"), 2)
111
+ self.assertTrue(sock.closed)
112
+
113
+ def test_transport_failure_is_reported_not_raised(self):
114
+ conn, _ = make_conn([BANNER, EHLO_OK])
115
+ conn.open()
116
+ conn._sock.chunks = [] # server dies mid-session
117
+ out = conn.probe("a@example.test")
118
+ self.assertTrue(out.transport_error)
119
+ self.assertIsNone(out.code)
120
+ self.assertTrue(out.retryable)
121
+
122
+ def test_unexpected_banner_is_not_ready(self):
123
+ conn, _ = make_conn([b"554 Service unavailable\r\n"])
124
+ conn.open()
125
+ self.assertFalse(conn.ready)
126
+
127
+ def test_greylist_code_marked_retryable(self):
128
+ conn, _ = make_conn(
129
+ [BANNER, EHLO_OK, b"250 OK\r\n", b"451 4.7.1 Greylisted, try later\r\n", b"250 OK\r\n"]
130
+ )
131
+ conn.open()
132
+ out = conn.probe("a@example.test")
133
+ self.assertEqual(out.code, 451)
134
+ self.assertTrue(out.retryable)
135
+ self.assertFalse(out.permanent_reject)
136
+
137
+
138
+ class RcptOutcomeTests(unittest.TestCase):
139
+ def test_flags_for_5xx(self):
140
+ o = RcptOutcome(code=550, message="550 no such user")
141
+ self.assertTrue(o.permanent_reject)
142
+ self.assertFalse(o.retryable)
143
+
144
+ def test_flags_for_accept(self):
145
+ o = RcptOutcome(code=250, message="250 OK")
146
+ self.assertTrue(o.accepted)
147
+ self.assertFalse(o.retryable)
148
+ self.assertFalse(o.permanent_reject)
149
+
150
+
151
+ if __name__ == "__main__":
152
+ unittest.main()