Files
webmail-client/backend/app/accounts/testing.py
T
lukasandClaude Opus 5.5 463f96ad57 Invite a friend; handle field shows the domain; system mail fixes
- Invitations: each user can invite two friends by email (sign-up works
  through the link even while registration is closed); admin-editable
  template, subject and sender.
- Invitation sender defaults to the system-mail From address, which the
  SMTP account is allowed to send as (was postmaster@APP_DOMAIN, refused
  with 553 when the two differ).
- Sign-in, sign-up and forgot-password fields show the fixed
  @domain after the typed name; the registration status reports it.
- System mail gets a Date header; the invitation's plain-text part keeps
  its paragraphs and line breaks.
- SMTP EHLO uses SMTP_HELO_NAME / APP_DOMAIN, not the container name.
- DNS recommendations for the mail domains.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-15 19:34:31 +02:00

108 lines
3.8 KiB
Python

"""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.config import smtp_helo_name
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,
local_hostname=smtp_helo_name(),
)
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,
public_only=True,
)
)
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)