Files
webmail-client/backend/app/accounts/testing.py
T

105 lines
3.7 KiB
Python
Raw Normal View History

2026-07-17 23:20:34 +02:00
"""Credential testing for the account wizard (SPEC §6.2 ``test(config, credentials)``).
Runs a full IMAP LOGIN + LIST and an SMTP EHLO + AUTH (no message sent), mapping
failures to precise user-facing codes. This is a §10.2 decryption-boundary sibling:
it handles plaintext credentials the user just typed, before they are encrypted.
"""
from __future__ import annotations
import socket
import ssl
import aiosmtplib
from app.accounts.ssrf import SsrfError, assert_host_is_public
from app.accounts.types import ServerConfig
from app.providers.base import ProviderAuthError, ProviderConnectError
from app.providers.imap_smtp import ImapSmtpProvider, ProviderConfig
_SMTP_TIMEOUT = 10.0
class AccountTestError(Exception):
"""A credential/connectivity test failed, with a precise ``code`` (SPEC §6.2)."""
def __init__(self, code: str, detail: str) -> None:
super().__init__(detail)
self.code = code
self.detail = detail
def _classify_cause(cause: BaseException | None) -> tuple[str, str]:
if isinstance(cause, ssl.SSLError):
return "tls_failed", str(cause)
if isinstance(cause, socket.gaierror):
return "unknown_host", str(cause)
if isinstance(cause, TimeoutError):
return "connect_timeout", "connection timed out"
return "connect_failed", str(cause or "connection failed")
async def _assert_public(config: ServerConfig, label: str) -> None:
try:
await assert_host_is_public(config.host)
except SsrfError as exc:
raise AccountTestError("host_not_allowed", f"{label} host is not permitted: {exc}") from exc
async def _test_smtp(config: ServerConfig, username: str, password: str) -> None:
smtp = aiosmtplib.SMTP(
hostname=config.host,
port=config.port,
use_tls=config.tls == "ssl",
start_tls=config.tls == "starttls",
timeout=_SMTP_TIMEOUT,
)
try:
await smtp.connect()
await smtp.login(username, password)
await smtp.quit()
except aiosmtplib.SMTPAuthenticationError as exc:
raise AccountTestError("auth_failed", f"SMTP authentication failed: {exc}") from exc
except aiosmtplib.SMTPConnectError as exc:
raise AccountTestError("connect_failed", f"SMTP connect failed: {exc}") from exc
except ssl.SSLError as exc:
raise AccountTestError("tls_failed", f"SMTP TLS failed: {exc}") from exc
except socket.gaierror as exc:
raise AccountTestError("unknown_host", f"SMTP host not found: {exc}") from exc
except (TimeoutError, aiosmtplib.SMTPTimeoutError) as exc:
raise AccountTestError("connect_timeout", "SMTP connection timed out") from exc
except aiosmtplib.SMTPException as exc:
raise AccountTestError("connect_failed", f"SMTP error: {exc}") from exc
async def test_account(
*, imap: ServerConfig, smtp: ServerConfig, username: str, password: str
) -> None:
"""Verify IMAP + SMTP credentials. Raises :class:`AccountTestError` on failure."""
await _assert_public(imap, "IMAP")
await _assert_public(smtp, "SMTP")
provider = ImapSmtpProvider(
ProviderConfig(
imap_host=imap.host,
imap_port=imap.port,
imap_tls=imap.tls,
smtp_host=smtp.host,
smtp_port=smtp.port,
smtp_tls=smtp.tls,
username=username,
password=password,
)
)
try:
await provider.verify() # IMAP LOGIN + LIST
except ProviderAuthError as exc:
raise AccountTestError("auth_failed", exc.detail) from exc
except ProviderConnectError as exc:
code, detail = _classify_cause(exc.__cause__)
raise AccountTestError(code, detail) from exc
finally:
await provider.close()
await _test_smtp(smtp, username, password)