You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
216 lines
8.3 KiB
Python
216 lines
8.3 KiB
Python
"""Validated SMTP settings and registration verification mail delivery.
|
|
|
|
The settings store deliberately uses the panel's encrypted record store. The
|
|
module never logs SMTP server responses because those can contain addresses or
|
|
authentication details supplied by a remote server.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import ipaddress
|
|
import json
|
|
import re
|
|
import smtplib
|
|
import ssl
|
|
from dataclasses import dataclass, field
|
|
from email.message import EmailMessage
|
|
from typing import Any, Mapping, Protocol
|
|
|
|
|
|
_DNS_LABEL = re.compile(r"[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?\Z")
|
|
_LOCAL_PART = re.compile(r"[A-Za-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[A-Za-z0-9!#$%&'*+/=?^_`{|}~-]+)*\Z")
|
|
_SIX_DIGITS = re.compile(r"[0-9]{6}\Z")
|
|
_SMTP_RECORD_TYPE = "smtp"
|
|
_SMTP_RECORD_KEY = "current"
|
|
|
|
|
|
class SMTPError(Exception):
|
|
"""Safe user-facing SMTP configuration or delivery failure."""
|
|
|
|
def __init__(self, message: str, status: int = 422) -> None:
|
|
super().__init__(message)
|
|
self.status = status
|
|
|
|
|
|
def _validate_host(host: str) -> str:
|
|
if (not isinstance(host, str) or not host or len(host) > 253
|
|
or host != host.strip()):
|
|
raise SMTPError("SMTP 服务器地址格式无效")
|
|
try:
|
|
ipaddress.ip_address(host)
|
|
return host
|
|
except ValueError:
|
|
pass
|
|
if not all(_DNS_LABEL.fullmatch(label) for label in host.split(".")):
|
|
raise SMTPError("SMTP 服务器地址必须是 IP 或 DNS 名称")
|
|
return host.lower()
|
|
|
|
|
|
def validate_email(address: str) -> str:
|
|
"""Accept a bare ASCII mailbox address, never a display name or header."""
|
|
|
|
if (not isinstance(address, str) or len(address) > 254
|
|
or address != address.strip() or address.count("@") != 1):
|
|
raise SMTPError("邮箱地址格式无效")
|
|
local, domain = address.rsplit("@", 1)
|
|
if (not local or len(local) > 64 or not _LOCAL_PART.fullmatch(local)
|
|
or not domain or len(domain) > 253
|
|
or not all(_DNS_LABEL.fullmatch(label) for label in domain.split("."))):
|
|
raise SMTPError("邮箱地址格式无效")
|
|
return f"{local}@{domain.lower()}"
|
|
|
|
|
|
@dataclass(frozen=True)
|
|
class SMTPConfig:
|
|
host: str
|
|
port: int
|
|
tls_mode: str
|
|
from_address: str
|
|
username: str = ""
|
|
password: str = field(default="", repr=False)
|
|
|
|
def __post_init__(self) -> None:
|
|
object.__setattr__(self, "host", _validate_host(self.host))
|
|
if (isinstance(self.port, bool) or not isinstance(self.port, int)
|
|
or not 1 <= self.port <= 65535):
|
|
raise SMTPError("SMTP 端口必须介于 1 到 65535")
|
|
if (not isinstance(self.tls_mode, str)
|
|
or self.tls_mode not in {"ssl", "starttls", "none"}):
|
|
raise SMTPError("SMTP 加密方式无效")
|
|
object.__setattr__(self, "from_address", validate_email(self.from_address))
|
|
if (not isinstance(self.username, str) or len(self.username) > 256
|
|
or self.username != self.username.strip()
|
|
or any(ord(char) < 32 or ord(char) == 127 for char in self.username)):
|
|
raise SMTPError("SMTP 用户名格式无效")
|
|
if not isinstance(self.password, str) or len(self.password) > 2048:
|
|
raise SMTPError("SMTP 密码格式无效")
|
|
if bool(self.username) != bool(self.password):
|
|
raise SMTPError("SMTP 用户名和密码必须同时填写")
|
|
if self.username and self.tls_mode == "none":
|
|
raise SMTPError("SMTP 账号认证必须启用 SSL 或 STARTTLS")
|
|
|
|
@classmethod
|
|
def from_mapping(cls, values: Mapping[str, Any]) -> SMTPConfig:
|
|
if not isinstance(values, Mapping):
|
|
raise SMTPError("SMTP 配置格式无效")
|
|
return cls(
|
|
host=values.get("host"),
|
|
port=values.get("port"),
|
|
tls_mode=values.get("tls_mode"),
|
|
from_address=values.get("from_address"),
|
|
username=values.get("username", ""),
|
|
password=values.get("password", ""),
|
|
)
|
|
|
|
def as_record(self) -> dict[str, str | int]:
|
|
"""Full value for the *encrypted* database record only."""
|
|
|
|
return {
|
|
"host": self.host,
|
|
"port": self.port,
|
|
"tls_mode": self.tls_mode,
|
|
"from_address": self.from_address,
|
|
"username": self.username,
|
|
"password": self.password,
|
|
}
|
|
|
|
def public_status(self) -> dict[str, str | int | bool]:
|
|
"""Admin-only status; intentionally never includes the SMTP password."""
|
|
|
|
return {
|
|
"configured": True,
|
|
"host": self.host,
|
|
"port": self.port,
|
|
"tls_mode": self.tls_mode,
|
|
"from_address": self.from_address,
|
|
"username": self.username,
|
|
"password_configured": bool(self.password),
|
|
}
|
|
|
|
|
|
class _RecordStore(Protocol):
|
|
def get(self, record_type: str, record_key: str) -> str | None: ...
|
|
def set(self, record_type: str, record_key: str, value: str) -> None: ...
|
|
|
|
|
|
class SMTPSettingsStore:
|
|
"""One SMTP configuration in the panel's AES-GCM-encrypted record table."""
|
|
|
|
def __init__(self, records: _RecordStore) -> None:
|
|
self._records = records
|
|
|
|
def get(self) -> SMTPConfig | None:
|
|
raw = self._records.get(_SMTP_RECORD_TYPE, _SMTP_RECORD_KEY)
|
|
if raw is None:
|
|
return None
|
|
try:
|
|
payload = json.loads(raw)
|
|
return SMTPConfig.from_mapping(payload)
|
|
except (ValueError, TypeError, SMTPError):
|
|
raise SMTPError("已保存的 SMTP 配置无效,请重新保存", status=503) from None
|
|
|
|
def save(self, values: Mapping[str, Any]) -> SMTPConfig:
|
|
if not isinstance(values, Mapping):
|
|
raise SMTPError("SMTP 配置格式无效")
|
|
candidate = dict(values)
|
|
if candidate.get("password") in (None, ""):
|
|
current = self.get()
|
|
if current is not None and candidate.get("username", "") == current.username:
|
|
candidate["password"] = current.password
|
|
else:
|
|
candidate["password"] = ""
|
|
config = SMTPConfig.from_mapping(candidate)
|
|
self._records.set(
|
|
_SMTP_RECORD_TYPE, _SMTP_RECORD_KEY,
|
|
json.dumps(config.as_record(), ensure_ascii=False, separators=(",", ":")),
|
|
)
|
|
return config
|
|
|
|
def public_status(self) -> dict[str, str | int | bool]:
|
|
config = self.get()
|
|
return {"configured": False} if config is None else config.public_status()
|
|
|
|
|
|
def send_verification_code(config: SMTPConfig, recipient_email: str, code: str, *,
|
|
timeout: int | float = 10) -> None:
|
|
"""Send one six-digit registration code; all transport errors are redacted."""
|
|
|
|
recipient = validate_email(recipient_email)
|
|
if not isinstance(code, str) or not _SIX_DIGITS.fullmatch(code):
|
|
raise SMTPError("验证码格式无效")
|
|
if (isinstance(timeout, bool) or not isinstance(timeout, (int, float))
|
|
or not 0 < timeout <= 30):
|
|
raise SMTPError("SMTP 连接超时设置无效")
|
|
|
|
message = EmailMessage()
|
|
message["From"] = config.from_address
|
|
message["To"] = recipient
|
|
message["Subject"] = "Virsh Panel 注册验证码"
|
|
message["Auto-Submitted"] = "auto-generated"
|
|
message.set_content(
|
|
f"您的注册验证码是:{code}\n\n验证码在 10 分钟内有效,请勿转发给他人。\n"
|
|
"如果不是您本人操作,请忽略这封邮件。\n",
|
|
charset="utf-8",
|
|
)
|
|
|
|
try:
|
|
context = ssl.create_default_context()
|
|
if config.tls_mode == "ssl":
|
|
client = smtplib.SMTP_SSL(
|
|
config.host, config.port, timeout=timeout, context=context,
|
|
)
|
|
else:
|
|
client = smtplib.SMTP(config.host, config.port, timeout=timeout)
|
|
with client:
|
|
client.ehlo()
|
|
if config.tls_mode == "starttls":
|
|
client.starttls(context=context)
|
|
client.ehlo()
|
|
if config.username:
|
|
client.login(config.username, config.password)
|
|
refused = client.send_message(message)
|
|
if refused:
|
|
raise SMTPError("验证码发送失败,请检查 SMTP 配置后重试", status=502)
|
|
except (smtplib.SMTPException, OSError):
|
|
raise SMTPError("验证码发送失败,请检查 SMTP 配置后重试", status=502) from None
|