File size: 12,179 Bytes
584ed90 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 | """Reusable outbound SMTP transport for the local Amazon clone.
No network delivery is configured by default. Supplying SMTP environment
variables switches registration, password-recovery, and order-confirmation
outboxes from ``LOCAL_ONLY`` to an asynchronous SMTP delivery attempt.
"""
from __future__ import annotations
import ipaddress
import os
import re
import smtplib
import ssl
from dataclasses import dataclass
from email.message import EmailMessage
from email.utils import getaddresses, parseaddr
from typing import Mapping
from urllib.parse import urlsplit
class SMTPConfigurationError(ValueError):
pass
@dataclass(frozen=True, repr=False)
class SMTPConfig:
host: str
port: int
security: str
sender: str
username: str | None = None
password: str | None = None
timeout_seconds: float = 10.0
mailbox_namespace: str | None = None
mailbox_capability: str | None = None
def __repr__(self) -> str:
return (
"SMTPConfig("
f"host={self.host!r}, port={self.port!r}, security={self.security!r}, "
f"sender={self.sender!r}, username={'<configured>' if self.username else None}, "
"password=<redacted>, "
f"timeout_seconds={self.timeout_seconds!r}, "
f"mailbox_namespace={self.mailbox_namespace!r}, "
"mailbox_capability=<redacted>)"
)
_SMTP_ENV_KEYS = (
"AMAZON_CLONE_SMTP_HOST",
"AMAZON_CLONE_SMTP_PORT",
"AMAZON_CLONE_SMTP_TLS",
"AMAZON_CLONE_SMTP_USERNAME",
"AMAZON_CLONE_SMTP_PASSWORD",
"AMAZON_CLONE_SMTP_FROM",
"AMAZON_CLONE_SMTP_TIMEOUT_SECONDS",
"AMAZON_CLONE_MAILBOX_NAMESPACE",
"AMAZON_CLONE_MAILBOX_CAPABILITY",
)
_REQUIRE_SMTP_ENV_KEY = "AMAZON_CLONE_REQUIRE_SMTP"
def _clean_header(value: str, field: str, *, max_bytes: int = 512) -> str:
cleaned = value.strip()
if (
not cleaned
or len(cleaned.encode("utf-8")) > max_bytes
or any(ord(character) < 32 or ord(character) == 127 for character in cleaned)
):
raise SMTPConfigurationError(f"{field} must be a non-empty single-line value")
return cleaned
def _clean_body(value: str) -> str:
if not isinstance(value, str) or len(value.encode("utf-8")) > 64 * 1024:
raise SMTPConfigurationError("message body must not exceed 64 KiB")
if any(
(ord(character) < 32 or ord(character) == 127)
and character not in {"\t", "\n", "\r"}
for character in value
):
raise SMTPConfigurationError("message body contains a forbidden control character")
return value
def _mailbox(value: str, field: str, *, allow_display_name: bool) -> str:
cleaned = _clean_header(value, field)
parsed_addresses = getaddresses([cleaned])
if len(parsed_addresses) != 1:
raise SMTPConfigurationError(f"{field} must contain one valid email address")
display_name, address = parseaddr(cleaned)
if (
parsed_addresses[0] != (display_name, address)
or not address
or address.count("@") != 1
or any(character.isspace() for character in address)
):
raise SMTPConfigurationError(f"{field} must contain one valid email address")
if not allow_display_name and (display_name or address != cleaned):
raise SMTPConfigurationError(f"{field} must be a bare email address")
return cleaned
def load_smtp_config(
environ: Mapping[str, str] | None = None,
) -> SMTPConfig | None:
"""Load strict SMTP configuration, or return ``None`` for LOCAL_ONLY mode."""
source = os.environ if environ is None else environ
require_value = source.get(_REQUIRE_SMTP_ENV_KEY, "0").strip().lower()
require_aliases = {
"": False,
"0": False,
"false": False,
"no": False,
"1": True,
"true": True,
"yes": True,
}
if require_value not in require_aliases:
raise SMTPConfigurationError(
"AMAZON_CLONE_REQUIRE_SMTP must be 1 or 0"
)
require_smtp = require_aliases[require_value]
host_value = source.get("AMAZON_CLONE_SMTP_HOST", "").strip()
any_smtp_value = any(source.get(key, "").strip() for key in _SMTP_ENV_KEYS)
if not host_value:
if require_smtp:
raise SMTPConfigurationError(
"AMAZON_CLONE_REQUIRE_SMTP=1 requires a complete SMTP configuration"
)
if any_smtp_value:
raise SMTPConfigurationError(
"AMAZON_CLONE_SMTP_HOST is required when any SMTP setting is present"
)
return None
host = _clean_header(host_value, "SMTP host")
tls_value = source.get("AMAZON_CLONE_SMTP_TLS", "starttls").strip().lower()
security_aliases = {
"1": "starttls",
"true": "starttls",
"yes": "starttls",
"starttls": "starttls",
"ssl": "ssl",
"implicit": "ssl",
"0": "plain",
"false": "plain",
"no": "plain",
"none": "plain",
"plain": "plain",
}
security = security_aliases.get(tls_value)
if security is None:
raise SMTPConfigurationError(
"AMAZON_CLONE_SMTP_TLS must be starttls, ssl, or none"
)
default_port = 465 if security == "ssl" else 587
try:
port = int(source.get("AMAZON_CLONE_SMTP_PORT", str(default_port)))
except ValueError as exc:
raise SMTPConfigurationError("SMTP port must be an integer") from exc
if not 1 <= port <= 65535:
raise SMTPConfigurationError("SMTP port must be between 1 and 65535")
username = source.get("AMAZON_CLONE_SMTP_USERNAME", "").strip() or None
password = source.get("AMAZON_CLONE_SMTP_PASSWORD", "") or None
if (username is None) != (password is None):
raise SMTPConfigurationError(
"SMTP username and password must be configured together"
)
if username is not None:
username = _clean_header(username, "SMTP username")
if security == "plain":
try:
parsed_host = ipaddress.ip_address(host.strip("[]"))
host_is_loopback = parsed_host.is_loopback
except ValueError:
host_is_loopback = host.casefold() in {
"localhost",
"mailbox-internal",
}
if not host_is_loopback:
raise SMTPConfigurationError(
"unencrypted SMTP is permitted only for a loopback mail server"
)
if username is not None:
raise SMTPConfigurationError(
"unencrypted SMTP cannot be configured with authentication"
)
sender = _mailbox(
source.get("AMAZON_CLONE_SMTP_FROM", ""),
"AMAZON_CLONE_SMTP_FROM",
allow_display_name=True,
)
try:
timeout_seconds = float(
source.get("AMAZON_CLONE_SMTP_TIMEOUT_SECONDS", "10")
)
except ValueError as exc:
raise SMTPConfigurationError("SMTP timeout must be numeric") from exc
if not 1 <= timeout_seconds <= 60:
raise SMTPConfigurationError("SMTP timeout must be between 1 and 60 seconds")
mailbox_namespace = source.get("AMAZON_CLONE_MAILBOX_NAMESPACE", "").strip() or None
mailbox_capability = source.get("AMAZON_CLONE_MAILBOX_CAPABILITY", "") or None
if (mailbox_namespace is None) != (mailbox_capability is None):
raise SMTPConfigurationError(
"mailbox namespace and capability must be configured together"
)
if mailbox_namespace is not None and (
len(mailbox_namespace) > 128
or re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9._-]*", mailbox_namespace) is None
):
raise SMTPConfigurationError("mailbox namespace is malformed")
if mailbox_capability is not None and len(mailbox_capability) < 32:
raise SMTPConfigurationError("mailbox capability is malformed")
return SMTPConfig(
host=host,
port=port,
security=security,
sender=sender,
username=username,
password=password,
timeout_seconds=timeout_seconds,
mailbox_namespace=mailbox_namespace,
mailbox_capability=mailbox_capability,
)
def smtp_public_summary(config: SMTPConfig | None) -> dict[str, object]:
if config is None:
return {"mode": "LOCAL_ONLY"}
return {
"mode": "SMTP",
"host": config.host,
"port": config.port,
"security": config.security,
"authentication": bool(config.username),
"sender": config.sender,
}
def load_local_inbox_url(
config: SMTPConfig | None,
environ: Mapping[str, str] | None = None,
) -> str | None:
"""Return a validated loopback inbox URL for the local capture profile."""
source = os.environ if environ is None else environ
raw = source.get("AMAZON_CLONE_LOCAL_INBOX_URL", "").strip()
if not raw:
return None
if config is None:
raise SMTPConfigurationError(
"AMAZON_CLONE_LOCAL_INBOX_URL requires SMTP configuration"
)
try:
config_host = ipaddress.ip_address(config.host.strip("[]"))
except ValueError as exc:
raise SMTPConfigurationError(
"AMAZON_CLONE_LOCAL_INBOX_URL is allowed only with loopback SMTP"
) from exc
if not config_host.is_loopback:
raise SMTPConfigurationError(
"AMAZON_CLONE_LOCAL_INBOX_URL is allowed only with loopback SMTP"
)
parsed = urlsplit(raw)
try:
port = parsed.port
except ValueError as exc:
raise SMTPConfigurationError("local inbox URL has an invalid port") from exc
if (
parsed.scheme != "http"
or parsed.hostname not in {"127.0.0.1", "::1"}
or port is None
or parsed.username is not None
or parsed.password is not None
or parsed.path not in {"", "/"}
or parsed.query
or parsed.fragment
):
raise SMTPConfigurationError(
"AMAZON_CLONE_LOCAL_INBOX_URL must be a loopback HTTP origin"
)
host = f"[{parsed.hostname}]" if parsed.hostname == "::1" else parsed.hostname
return f"http://{host}:{port}/"
def send_smtp_message(
config: SMTPConfig,
*,
recipient: str,
subject: str,
body: str,
) -> None:
"""Send one plain-text message without logging credentials or message content."""
safe_recipient = _mailbox(recipient, "recipient", allow_display_name=False)
safe_subject = _clean_header(subject, "subject")
safe_body = _clean_body(body)
message = EmailMessage()
message["From"] = config.sender
message["To"] = safe_recipient
message["Subject"] = safe_subject
if config.mailbox_namespace is not None:
assert config.mailbox_capability is not None
message["X-WebsiteBench-Namespace"] = config.mailbox_namespace
message["X-WebsiteBench-Capability"] = config.mailbox_capability
message.set_content(safe_body)
context = ssl.create_default_context()
if config.security == "ssl":
client: smtplib.SMTP = smtplib.SMTP_SSL(
config.host,
config.port,
timeout=config.timeout_seconds,
context=context,
)
else:
client = smtplib.SMTP(
config.host, config.port, timeout=config.timeout_seconds
)
with client:
client.ehlo()
if config.security == "starttls":
client.starttls(context=context)
client.ehlo()
if config.username is not None:
assert config.password is not None
client.login(config.username, config.password)
client.send_message(message)
def smtp_error_summary(error: BaseException) -> str:
"""Return an admin-safe failure category without exception text or secrets."""
name = type(error).__name__
if isinstance(error, smtplib.SMTPResponseException):
return f"{name}:smtp-{int(error.smtp_code)}"
return name[:96] or "SMTPDeliveryError"
__all__ = [
"SMTPConfig",
"SMTPConfigurationError",
"load_local_inbox_url",
"load_smtp_config",
"send_smtp_message",
"smtp_error_summary",
"smtp_public_summary",
]
|