From 63efb9f20442893405acfd4abac5090673ef6187 Mon Sep 17 00:00:00 2001 From: Peter van Arkel Date: Fri, 4 Dec 2026 13:56:46 +0100 Subject: [PATCH] Configure outgoing panel email for linked mail deployments --- deploy/panel_installer/cli.py | 2 + deploy/panel_installer/cluster.py | 29 ++- deploy/panel_installer/cluster_wizard.py | 61 +++++++ deploy/panel_installer/config.py | 84 ++++++++- deploy/panel_installer/engine.py | 63 ++++++- docs/deployment.md | 33 +++- src/coulobre/hosting/account_security.py | 6 +- src/coulobre/hosting/installation_views.py | 4 +- src/coulobre/hosting/invitations.py | 27 ++- .../migrations/0097_panel_mail_relay.py | 32 ++++ src/coulobre/hosting/models.py | 9 + src/coulobre/hosting/notifications.py | 3 +- src/coulobre/hosting/panel_factors.py | 5 +- src/coulobre/hosting/panel_mail.py | 75 ++++++++ src/coulobre/hosting/panel_mail_views.py | 168 ++++++++++++++++++ src/coulobre/hosting/password_reset.py | 3 +- .../hosting/feature_configuration.html | 4 + .../templates/hosting/manage_invitation.html | 5 + .../hosting/panel_mail_settings.html | 41 +++++ src/coulobre/hosting/test_panel_mail.py | 84 +++++++++ src/coulobre/hosting/urls.py | 6 + src/coulobre/hosting/workspaces.py | 3 +- src/coulobre/settings.py | 3 +- tests/test_cluster_installer.py | 2 + 24 files changed, 723 insertions(+), 29 deletions(-) create mode 100644 src/coulobre/hosting/migrations/0097_panel_mail_relay.py create mode 100644 src/coulobre/hosting/panel_mail.py create mode 100644 src/coulobre/hosting/panel_mail_views.py create mode 100644 src/coulobre/hosting/templates/hosting/panel_mail_settings.html create mode 100644 src/coulobre/hosting/test_panel_mail.py diff --git a/deploy/panel_installer/cli.py b/deploy/panel_installer/cli.py index 8a465e1..ebbc5ea 100644 --- a/deploy/panel_installer/cli.py +++ b/deploy/panel_installer/cli.py @@ -62,6 +62,8 @@ def export_parameters(plan, password_path): "admin": admin, "hosting": plan.hosting.parameters(), } + if plan.smtp: + parameters["smtp"] = plan.record()["smtp"] for name, role in (("dns", plan.dns), ("mail", plan.mail)): fields = parameters[name] = {"mode": role.mode} if role.mode in REMOTE_MODES: diff --git a/deploy/panel_installer/cluster.py b/deploy/panel_installer/cluster.py index 6e4e22c..c0c2cd6 100644 --- a/deploy/panel_installer/cluster.py +++ b/deploy/panel_installer/cluster.py @@ -21,8 +21,10 @@ from .config import ( keys, parse_plan, read_password, + read_smtp_password, read_ssh_host_key, role, + smtp_credential, ) STATE = Path("/var/lib/coulobre-cluster") @@ -63,6 +65,10 @@ class Cluster: yield ( f" DNS {panel.plan.dns.mode} · Mail {panel.plan.mail.mode}" ) + if relay := panel.plan.smtp: + yield f" Panel SMTP: {relay.host}:{relay.port}" + elif panel.plan.mail.mode == "remote": + yield " Panel SMTP: configure after installation" if panel.domains: yield " Domain scope: " + ", ".join(panel.domains) for name, receiver in self.receivers.items(): @@ -107,7 +113,7 @@ def parse_cluster(data): def parse_panel(entry, index, receivers, sending): keys( entry, - {"name", "panel", "admin", "hosting", "dns", "ssh", "domains"}, + {"name", "panel", "admin", "hosting", "dns", "ssh", "domains", "smtp"}, "cluster panel", ) name = entry.get("name", "") @@ -141,6 +147,8 @@ def parse_panel(entry, index, receivers, sending): "dns": {"mode": dns}, "mail": {"mode": "off"}, } + if "smtp" in entry: + params["smtp"] = entry["smtp"] pins = {} for service, receiver in receivers.items(): if service == "dns" and dns != "shared": @@ -279,6 +287,11 @@ def run_remote_step(settings): if action == "cluster-keys" else print, scopes=settings["scopes"], + smtp_password=( + smtp_credential(settings.get("smtp_password")) + if plan.smtp and action == "cluster-panel" + else None + ), ) remote.check_panel_destination() installer.check_state() @@ -352,6 +365,9 @@ class ClusterInstaller: } def check(self): + for panel in self.cluster.panels: + if panel.plan.smtp: + read_smtp_password(panel.plan.smtp.password_file) self.progress("Checking the local panel.") self.local.check_state() remote.check_panel_destination() @@ -501,7 +517,16 @@ class ClusterInstaller: | { "role": "cluster-panel", "password": self.passwords[panel.name], - }, + } + | ( + { + "smtp_password": read_smtp_password( + panel.plan.smtp.password_file + ) + } + if panel.plan.smtp + else {} + ), ) diff --git a/deploy/panel_installer/cluster_wizard.py b/deploy/panel_installer/cluster_wizard.py index 66393cb..ffcf2a5 100644 --- a/deploy/panel_installer/cluster_wizard.py +++ b/deploy/panel_installer/cluster_wizard.py @@ -4,15 +4,19 @@ from . import guidance from .cluster import SCOPE, ClusterInstaller, parse_cluster from .config import ( InstallError, + admin_email, comma_separated, file_path, hostname, read_password, + read_smtp_password, + smtp_credential, ) from .interactive import ( InteractiveSetup, ask_checked, local_path, + typed_port, validated_list, ) from .terminal import PreviousStepError @@ -167,9 +171,66 @@ def collect_hosting(terminal, name, previous, receivers): "receiver access without permitting domain changes." ), ) + if relay := collect_smtp(terminal, previous.get("smtp"), receivers): + result["smtp"] = relay return result +def collect_smtp(terminal, previous, receivers): + if ( + terminal.choose( + "Outgoing panel email", + ("later", "smtp"), + "smtp" if previous else "later", + hint="Used for welcome email and account security. A shared " + "mail receiver does not create an SMTP login for the panel.", + ) + == "later" + ): + return {} + previous = previous or {} + mail = receivers.get("mail", {}) + + def private_path(value): + path = local_path(value) + read_smtp_password(path) + return path + + return { + "host": ask_checked( + terminal, + "SMTP hostname", + previous.get("host") or mail.get("mail_hostname", ""), + lambda value: hostname(value, "SMTP"), + ), + "port": ask_checked( + terminal, + "SMTP STARTTLS port", + str(previous.get("port", 587)), + lambda value: typed_port(value, "SMTP", 587), + ), + "username": ask_checked( + terminal, + "SMTP username", + previous.get("username", ""), + smtp_credential, + ), + "sender": ask_checked( + terminal, + "Panel From address", + previous.get("sender", ""), + admin_email, + ), + "password_file": ask_checked( + terminal, + "Private SMTP password file", + previous.get("password_file", ""), + private_path, + hint="Use an absolute path to a private file on this machine.", + ), + } + + def shared_ssh_defaults(connection): return { field: connection[field] diff --git a/deploy/panel_installer/config.py b/deploy/panel_installer/config.py index 8455a24..786148f 100644 --- a/deploy/panel_installer/config.py +++ b/deploy/panel_installer/config.py @@ -303,6 +303,55 @@ def hosting_defaults(table): ) +@dataclass(frozen=True) +class OutgoingSMTP: + host: str + port: int + username: str + sender: str + password_file: str + + +def smtp_credential(value): + if ( + not isinstance(value, str) + or not 1 <= len(value) <= 1024 + or any(not 32 <= ord(char) <= 126 for char in value) + ): + raise InstallError("Use a single-line ASCII SMTP credential.") + return value + + +def parse_smtp(table): + if table is None: + return None + keys( + table, {"host", "port", "username", "sender", "password_file"}, "smtp" + ) + sender = table.get("sender") + if ( + not isinstance(sender, str) + or len(sender) > 254 + or not re.fullmatch(r"[a-zA-Z0-9._+%=-]+@[a-zA-Z0-9.-]+", sender) + ): + raise InstallError("Enter a valid From address for panel email.") + sender = ( + sender.rsplit("@", 1)[0] + + "@" + + hostname(sender.rsplit("@", 1)[1], "sender") + ) + username = smtp_credential(table.get("username")) + if not username.strip() or len(username) > 254: + raise InstallError("Enter a valid SMTP username.") + return OutgoingSMTP( + hostname(table.get("host"), "SMTP"), + port(table.get("port"), "SMTP", 587), + username, + sender, + file_path(table.get("password_file"), "the SMTP password file"), + ) + + @dataclass(frozen=True) class Plan: hostname: str @@ -317,6 +366,7 @@ class Plan: dns: Role mail: Role hosting: HostingDefaults = HostingDefaults() + smtp: OutgoingSMTP | None = None def description(self): def target(role): @@ -337,14 +387,27 @@ class Plan: summary += " · Mail sending IPs " + ", ".join( self.hosting.mail_sending_addresses ) + if self.smtp: + summary += f" · Panel SMTP {self.smtp.host}:{self.smtp.port}" + elif self.mail.mode == "local": + summary += " · Panel SMTP local Postfix" + else: + summary += " · Panel SMTP not configured" return summary def record(self): - return {**asdict(self), "hosting": self.hosting.parameters()} + data = {**asdict(self), "hosting": self.hosting.parameters()} + if self.smtp is None: + data.pop("smtp") + return data def parse_plan(data, *, remote=False): - keys(data, {"panel", "admin", "dns", "mail", "hosting"}, "installation") + keys( + data, + {"panel", "admin", "dns", "mail", "hosting", "smtp"}, + "installation", + ) panel = data.get("panel") admin = data.get("admin") keys(admin, {"username", "email", "password_file"}, "admin") @@ -399,6 +462,7 @@ def parse_plan(data, *, remote=False): role(data.get("dns", {}), "dns"), mail, defaults, + parse_smtp(data.get("smtp")), ) @@ -423,10 +487,10 @@ def check_password(password): return password -def read_password(path): +def read_private_password(path, label): try: fd = os.open( - file_path(path, "the administrator password file"), + file_path(path, f"the {label} password file"), os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK, ) with os.fdopen(fd, "rb") as source: @@ -441,9 +505,17 @@ def read_password(path): password = source.read(4098).decode("utf-8").removesuffix("\n") except (OSError, ValueError): raise InstallError( - "Use a root-owned administrator password file with mode 0600." + f"Use a root-owned {label} password file with mode 0600." ) from None - return check_password(password) + return password + + +def read_password(path): + return check_password(read_private_password(path, "administrator")) + + +def read_smtp_password(path): + return smtp_credential(read_private_password(path, "SMTP")) def platform_settings(): diff --git a/deploy/panel_installer/engine.py b/deploy/panel_installer/engine.py index aad6bd5..c8bdb97 100644 --- a/deploy/panel_installer/engine.py +++ b/deploy/panel_installer/engine.py @@ -6,6 +6,7 @@ import pwd import secrets import smtplib import socket +import ssl import stat import subprocess import sys @@ -17,7 +18,12 @@ from tempfile import TemporaryDirectory from threading import Event, Thread from . import certificates, roles -from .config import REMOTE_MODES, InstallError, platform_settings +from .config import ( + REMOTE_MODES, + InstallError, + platform_settings, + read_smtp_password, +) SOURCE = Path(__file__).resolve().parents[2] ASSETS = SOURCE / "deploy" @@ -340,10 +346,18 @@ def install_lock(): class Installer: def __init__( - self, plan, password, progress, *, heartbeat=False, scopes=None + self, + plan, + password, + progress, + *, + heartbeat=False, + scopes=None, + smtp_password=None, ): self.plan = plan self.password = password + self.smtp_password = smtp_password self.progress = progress self.heartbeat = heartbeat self.scopes = scopes or {} @@ -687,7 +701,16 @@ class Installer: COULOBRE_MAIL_IMAP_HOST=self.plan.mail.mail_hostname, COULOBRE_MAIL_SUBMISSION_HOST=self.plan.mail.mail_hostname, ) - if self.plan.mail.mode == "local": + if relay := self.plan.smtp: + options.update( + COULOBRE_SMTP_HOST=relay.host, + COULOBRE_SMTP_PORT=str(relay.port), + COULOBRE_SMTP_STARTTLS="1", + COULOBRE_SMTP_USER=json.dumps(relay.username), + COULOBRE_SMTP_PASSWORD=json.dumps(self.relay_password()), + COULOBRE_EMAIL_FROM=relay.sender, + ) + elif self.plan.mail.mode == "local": options.update( COULOBRE_SMTP_HOST="127.0.0.1", COULOBRE_SMTP_PORT="25", @@ -713,7 +736,35 @@ class Installer: ) return "".join(f"{key}={value}\n" for key, value in options.items()) + def relay_password(self): + if self.smtp_password is not None: + return self.smtp_password + return read_smtp_password(self.plan.smtp.password_file) + def verify_notification_mail(self): + if configured := self.plan.smtp: + try: + with smtplib.SMTP( + configured.host, configured.port, timeout=8 + ) as relay: + relay.starttls(context=ssl.create_default_context()) + relay.login(configured.username, self.relay_password()) + status, _ = relay.mail(configured.sender) + relay.rset() + if status != 250: + raise OSError("SMTP sender rejected.") + except (OSError, ValueError): + self.progress( + "Outgoing SMTP could not be verified. Check the relay " + "hostname, STARTTLS, credentials and sender in Operator " + "Settings, then send a test email." + ) + else: + self.progress( + "Outgoing SMTP accepted the sender. Send a test email " + "from Operator Settings to check delivery." + ) + return if self.plan.mail.mode != "local": return try: @@ -855,6 +906,8 @@ class Installer: ) def install(self): + if self.plan.smtp: + self.smtp_password = self.relay_password() if os.geteuid() != 0 or not Path("/run/systemd/system").is_dir(): raise InstallError("Run the installer as root on a systemd host.") with install_lock(): @@ -1006,8 +1059,8 @@ class Installer: systemctl("reload", "apache2.service") systemctl("enable", "--now", HEALTH_TIMER) self.verify_panel() - if self.plan.mail.mode == "local": - with self.step("Checking Postfix for outgoing panel email"): + if self.plan.smtp or self.plan.mail.mode == "local": + with self.step("Checking outgoing panel email"): self.verify_notification_mail() for key in ("secret_key", "database_password", "broker_password"): self.state.pop(key, None) diff --git a/docs/deployment.md b/docs/deployment.md index 84fafec..f6b03b9 100644 --- a/docs/deployment.md +++ b/docs/deployment.md @@ -611,7 +611,38 @@ to use Postfix on the loopback interface. The installation check verifies that Postfix accepts an outbound SMTP envelope. Verify delivery to an inbox you control before inviting customers. -Set `COULOBRE_SMTP_HOST`, `COULOBRE_SMTP_PORT`, and +A linked mail receiver provisions hosted mailboxes. It does not by itself +give the panel a sender or permission to send welcome email, password +resets, or notifications. In the interactive cluster installer, set +**Outgoing panel email** on each panel if you already have an authorized +SMTP login. Otherwise choose **later**, then open **Operator Settings → +Email → Outgoing panel email** as an operator with a verified second +factor. Use the same relay on multiple panels if desired, with separate +SMTP logins where you want to revoke a single panel's access. + +For an automated install, use this optional TOML section. In a cluster +plan, use `[cluster.panels.smtp]` under the corresponding panel instead. + +```toml +[smtp] +host = "submission.example.net" +port = 587 +username = "panel-web1" +sender = "panel@example.net" +password_file = "/root/panel-web1.smtp-password" +``` + +The password file must be private and is read on the initiating server. +The installer uses STARTTLS and checks whether the relay accepts the +sender without delivering a message. The operator's **Send test email** +action submits an actual message to the specified test recipient. A +successful submission is not proof of inbox delivery. For the From +address, use a domain and sender permitted by the relay. The separate +welcome email sender settings only change message headers. + +Installed settings are the fallback when no relay is saved in the panel. +For environments managed directly by an operator, set +`COULOBRE_SMTP_HOST`, `COULOBRE_SMTP_PORT`, and `COULOBRE_EMAIL_FROM` in the panel environment. Add the relay's username and password if it requires authentication. The default uses STARTTLS on port 587. Keep the environment file restricted to the service operators. diff --git a/src/coulobre/hosting/account_security.py b/src/coulobre/hosting/account_security.py index 50dc7f9..47df290 100644 --- a/src/coulobre/hosting/account_security.py +++ b/src/coulobre/hosting/account_security.py @@ -4,7 +4,6 @@ from smtplib import SMTPException import django_otp from django import forms -from django.conf import settings from django.contrib import messages from django.contrib.auth import update_session_auth_hash from django.contrib.auth.hashers import check_password @@ -40,6 +39,7 @@ from .panel_factors import ( send_factor_code, user_devices, ) +from .panel_mail import outgoing_mail_available from .panel_sessions import ( preserve_session, record_security_event, @@ -74,7 +74,7 @@ class AccountSecurityView(AccountSecurityMixin, TemplateView): return super().get_context_data( factor=factor, factor_enabled=device is not None, - email_available=bool(settings.EMAIL_HOST), + email_available=bool(outgoing_mail_available()), events=PanelSecurityEvent.objects.filter(user=user).order_by( "-id" )[:10], @@ -266,7 +266,7 @@ class ChangeEmailView(AuthorizedSecurityChange): form_class = EmailForm def dispatch(self, request, *args, **kwargs): - if not settings.EMAIL_HOST: + if not outgoing_mail_available(): raise PermissionDenied return super().dispatch(request, *args, **kwargs) diff --git a/src/coulobre/hosting/installation_views.py b/src/coulobre/hosting/installation_views.py index dec3948..cf44068 100644 --- a/src/coulobre/hosting/installation_views.py +++ b/src/coulobre/hosting/installation_views.py @@ -517,7 +517,9 @@ class InvitationMailSettingsView(UserPassesTestMixin, FormView): } def get_context_data(self, **kwargs): - _, installed_address = parseaddr(settings.DEFAULT_FROM_EMAIL) + from .panel_mail import default_sender + + _, installed_address = parseaddr(default_sender()) return super().get_context_data( installed_address=installed_address, **kwargs ) diff --git a/src/coulobre/hosting/invitations.py b/src/coulobre/hosting/invitations.py index 65c5d5d..6012ed9 100644 --- a/src/coulobre/hosting/invitations.py +++ b/src/coulobre/hosting/invitations.py @@ -41,6 +41,7 @@ from .models import ( Reseller, ) from .panel_factors import lock_user +from .panel_mail import default_sender from .password_reset import reset_enabled INVITATION_AGE = timedelta(hours=48) @@ -214,7 +215,7 @@ def invitation_email(recipient, context): InvitationMailSettings.objects.filter(pk=1).first() or InvitationMailSettings() ) - sender = settings.DEFAULT_FROM_EMAIL + sender = default_sender() if mail_settings.sender_name or mail_settings.sender_address: name, address = parseaddr(sender) sender = sanitize_address( @@ -368,13 +369,29 @@ class ManageInvitation(AccessMixin, FormView): def get_context_data(self, **kwargs): user = self.record.user - can_send = user.is_active and not user.has_usable_password() + eligible = user.is_active and not user.has_usable_password() + transport = reset_enabled() + operator = self.request.user.is_superuser + if eligible and not transport: + delivery_blocker = ( + "Configure outgoing panel email first." + if operator + else "Ask your server administrator to set up outgoing email." + ) + elif eligible and not user.email: + delivery_blocker = ( + "Save a contact email before sending an invitation." + ) + else: + delivery_blocker = "" return super().get_context_data( login_user=user, invitation=getattr(user, "panel_invitation", None), - can_send=can_send, + can_send=eligible and transport and bool(user.email), + delivery_blocker=delivery_blocker, + can_configure_delivery=operator and not transport, welcome_preview=( - invitation_message_context(user) if can_send else None + invitation_message_context(user) if eligible else None ), **kwargs, ) @@ -396,6 +413,6 @@ class ManageInvitation(AccessMixin, FormView): return self.handle_no_permission() user.email = form.cleaned_data["email"] user.save(update_fields=["email"]) - if "invite" in self.request.POST: + if "invite" in self.request.POST and reset_enabled(): queue_invitation(user) return redirect(self.request.path) diff --git a/src/coulobre/hosting/migrations/0097_panel_mail_relay.py b/src/coulobre/hosting/migrations/0097_panel_mail_relay.py new file mode 100644 index 0000000..bdf6bbb --- /dev/null +++ b/src/coulobre/hosting/migrations/0097_panel_mail_relay.py @@ -0,0 +1,32 @@ +# Generated by Django 5.2.19 on 2026-12-04 12:51 + +from django.db import migrations, models + + +class Migration(migrations.Migration): + dependencies = [ + ("hosting", "0096_mailboximport_consecutive_retries_and_more"), + ] + + operations = [ + migrations.CreateModel( + name="PanelMailRelay", + fields=[ + ( + "id", + models.BigAutoField( + auto_created=True, + primary_key=True, + serialize=False, + verbose_name="ID", + ), + ), + ("host", models.CharField(max_length=253)), + ("port", models.PositiveIntegerField(default=587)), + ("username", models.CharField(max_length=254)), + ("sealed_password", models.TextField(editable=False)), + ("sender", models.EmailField(max_length=254)), + ("tested_at", models.DateTimeField(blank=True, null=True)), + ], + ), + ] diff --git a/src/coulobre/hosting/models.py b/src/coulobre/hosting/models.py index edbe491..518eb6e 100644 --- a/src/coulobre/hosting/models.py +++ b/src/coulobre/hosting/models.py @@ -200,6 +200,15 @@ class PanelInvitation(models.Model): ) +class PanelMailRelay(models.Model): + host = models.CharField(max_length=253) + port = models.PositiveIntegerField(default=587) + username = models.CharField(max_length=254) + sealed_password = models.TextField(editable=False) + sender = models.EmailField() + tested_at = models.DateTimeField(null=True, blank=True) + + class InvitationMailSettings(models.Model): sender_name = models.CharField( max_length=120, diff --git a/src/coulobre/hosting/notifications.py b/src/coulobre/hosting/notifications.py index 280ddd1..e511ea7 100644 --- a/src/coulobre/hosting/notifications.py +++ b/src/coulobre/hosting/notifications.py @@ -26,13 +26,14 @@ from .models import ( WebActivation, WebsiteRestoreJob, ) +from .panel_mail import outgoing_mail_available State = PanelNotification.State ATTEMPT_TIMEOUT = timedelta(minutes=5) def notifications_available(): - return bool(settings.EMAIL_HOST and settings.PASSWORD_RESET_ORIGIN) + return bool(outgoing_mail_available() and settings.PASSWORD_RESET_ORIGIN) def queue_notification( diff --git a/src/coulobre/hosting/panel_factors.py b/src/coulobre/hosting/panel_factors.py index 1aaffd6..326cfed 100644 --- a/src/coulobre/hosting/panel_factors.py +++ b/src/coulobre/hosting/panel_factors.py @@ -22,6 +22,7 @@ from .models import ( PanelRecoveryCode, PanelSecurityEvent, ) +from .panel_mail import outgoing_mail_available from .panel_sessions import ( SESSION_VERSION, record_security_event, @@ -90,7 +91,7 @@ def device_for_user(user, device_id, *, confirmed): def email_factor_available(user): - if not settings.EMAIL_HOST or not user.email: + if not outgoing_mail_available() or not user.email: return False try: validate_email(user.email) @@ -286,7 +287,7 @@ def send_factor_code(user, device_id, *, confirmed): if ( not isinstance(device, EmailDevice) or not device.email - or not settings.EMAIL_HOST + or not outgoing_mail_available() ): return "Email codes are unavailable for this account." allowed, _ = device.generate_is_allowed() diff --git a/src/coulobre/hosting/panel_mail.py b/src/coulobre/hosting/panel_mail.py new file mode 100644 index 0000000..40bc42c --- /dev/null +++ b/src/coulobre/hosting/panel_mail.py @@ -0,0 +1,75 @@ +"""Send panel email independently of customer mail provisioning.""" + +from base64 import urlsafe_b64encode +from hashlib import sha256 + +from cryptography.fernet import Fernet, InvalidToken, MultiFernet +from django.conf import settings +from django.core.mail.backends.smtp import EmailBackend +from django.views.decorators.debug import sensitive_variables + +from .models import PanelMailRelay + + +def saved_relay(): + return PanelMailRelay.objects.filter(pk=1).first() + + +def outgoing_mail_available(): + return ( + bool(settings.EMAIL_HOST) + or PanelMailRelay.objects.filter(pk=1).exists() + ) + + +def default_sender(): + relay = saved_relay() + return relay.sender if relay else settings.DEFAULT_FROM_EMAIL + + +def encryption(): + return MultiFernet( + [ + Fernet( + urlsafe_b64encode( + sha256( + b"coulobre-panel-relay-v1\0" + key.encode() + ).digest() + ) + ) + for key in (settings.SECRET_KEY, *settings.SECRET_KEY_FALLBACKS) + ] + ) + + +@sensitive_variables() +def relay_password(relay): + try: + return encryption().decrypt(relay.sealed_password.encode()).decode() + except (InvalidToken, UnicodeError): + raise OSError("Re-enter the outgoing relay password.") from None + + +class PanelEmailBackend(EmailBackend): + @sensitive_variables() + def __init__(self, **kwargs): + relay = saved_relay() + self.panel_sender = relay.sender if relay else None + if relay: + kwargs.update( + host=relay.host, + port=relay.port, + username=relay.username, + password=relay_password(relay), + use_tls=True, + use_ssl=False, + ) + super().__init__(**kwargs) + + def send_messages(self, email_messages): + messages = list(email_messages or ()) + if self.panel_sender: + for message in messages: + if message.from_email == settings.DEFAULT_FROM_EMAIL: + message.from_email = self.panel_sender + return super().send_messages(messages) diff --git a/src/coulobre/hosting/panel_mail_views.py b/src/coulobre/hosting/panel_mail_views.py new file mode 100644 index 0000000..b370848 --- /dev/null +++ b/src/coulobre/hosting/panel_mail_views.py @@ -0,0 +1,168 @@ +from email.utils import parseaddr + +from django import forms +from django.conf import settings +from django.contrib import messages +from django.contrib.admin.models import CHANGE, LogEntry +from django.contrib.auth.mixins import UserPassesTestMixin +from django.core.mail import send_mail +from django.db import transaction +from django.shortcuts import redirect +from django.urls import reverse_lazy +from django.utils import timezone +from django.utils.decorators import method_decorator +from django.views.decorators.cache import never_cache +from django.views.decorators.debug import ( + sensitive_post_parameters, + sensitive_variables, +) +from django.views.generic import FormView + +from coulobre.domain_names import canonical_domain + +from .access import OperatorOnlyMixin +from .models import PanelMailRelay +from .panel_mail import default_sender, encryption, saved_relay +from .sign_in_limits import limit_attempt + + +class SMTPRelayForm(forms.Form): + host = forms.CharField(label="SMTP hostname", max_length=253) + port = forms.IntegerField(min_value=1, max_value=65535, initial=587) + username = forms.CharField(label="SMTP username", max_length=254) + password = forms.CharField( + label="SMTP password", + max_length=1024, + strip=False, + widget=forms.PasswordInput(attrs={"autocomplete": "new-password"}), + ) + sender = forms.EmailField(label="Panel From address") + + def clean_host(self): + try: + return canonical_domain(self.cleaned_data["host"]) + except ValueError: + raise forms.ValidationError( + "Enter the relay's fully qualified hostname." + ) from None + + @sensitive_variables() + def clean(self): + values = super().clean() + for field in ("username", "password"): + value = values.get(field) + if value is not None and ( + not value.strip() + or any(not 32 <= ord(char) <= 126 for char in value) + ): + self.add_error( + field, "Use a single-line ASCII SMTP credential." + ) + return values + + +class TestPanelMailForm(forms.Form): + recipient = forms.EmailField(label="Test recipient") + + +@method_decorator(never_cache, name="dispatch") +@method_decorator(sensitive_post_parameters(), name="dispatch") +class PanelMailView(OperatorOnlyMixin, UserPassesTestMixin, FormView): + form_class = SMTPRelayForm + template_name = "hosting/panel_mail_settings.html" + success_url = reverse_lazy("panel:panel_mail_settings") + + def test_func(self): + return ( + self.request.user.is_superuser and self.request.user.is_verified() + ) + + def get_initial(self): + if relay := saved_relay(): + return { + name: getattr(relay, name) + for name in ("host", "port", "username", "sender") + } + return {} + + def get_context_data(self, **kwargs): + kwargs.setdefault("test_form", TestPanelMailForm()) + return super().get_context_data( + relay=saved_relay(), + installed=bool(settings.EMAIL_HOST), + sender=parseaddr(default_sender())[1], + **kwargs, + ) + + def post(self, request, *args, **kwargs): + if "reset_relay" in request.POST: + PanelMailRelay.objects.filter(pk=1).delete() + messages.success(request, "Restored the installed transport.") + return redirect(self.get_success_url()) + if "test_relay" in request.POST: + return self.test_delivery(request) + return super().post(request, *args, **kwargs) + + def test_delivery(self, request): + form = TestPanelMailForm(request.POST) + relay = saved_relay() + if not (relay or settings.EMAIL_HOST): + form.add_error(None, "Set up outgoing panel email first.") + if not form.is_valid(): + return self.render_to_response( + self.get_context_data( + form=self.get_form_class()(initial=self.get_initial()), + test_form=form, + ) + ) + limited = limit_attempt( + request, + "panel-smtp-test", + str(request.user.pk), + address_limit=10, + identity_limit=5, + ) + if limited: + return limited + try: + sent = send_mail( + "Coulobre Panel email test", + "Coulobre Panel sent this message to test outgoing email.", + default_sender(), + [form.cleaned_data["recipient"]], + ) + except (OSError, ValueError): + sent = 0 + if sent == 1: + if relay: + PanelMailRelay.objects.filter( + pk=relay.pk, sealed_password=relay.sealed_password + ).update(tested_at=timezone.now()) + messages.success( + request, + "SMTP accepted the message. Check the recipient's inbox.", + ) + else: + messages.error( + request, + "SMTP did not accept the message. Check the hostname, " + "STARTTLS, credentials and sender address.", + ) + return redirect(self.get_success_url()) + + @transaction.atomic + @sensitive_variables() + def form_valid(self, form): + values = form.cleaned_data.copy() + values["sealed_password"] = ( + encryption().encrypt(values.pop("password").encode()).decode() + ) + values["tested_at"] = None + relay, _ = PanelMailRelay.objects.update_or_create( + pk=1, defaults=values + ) + LogEntry.objects.log_actions( + self.request.user.pk, [relay], CHANGE, "Updated panel SMTP relay." + ) + messages.success(self.request, "Relay saved. Send a test email next.") + return super().form_valid(form) diff --git a/src/coulobre/hosting/password_reset.py b/src/coulobre/hosting/password_reset.py index 8fd3037..9101487 100644 --- a/src/coulobre/hosting/password_reset.py +++ b/src/coulobre/hosting/password_reset.py @@ -16,11 +16,12 @@ from django.views.decorators.cache import never_cache from kombu.exceptions import OperationalError from .panel_factors import lock_user, privileged_user +from .panel_mail import outgoing_mail_available from .sign_in_limits import limit_attempt def reset_enabled(): - return bool(settings.PASSWORD_RESET_ORIGIN and settings.EMAIL_HOST) + return bool(settings.PASSWORD_RESET_ORIGIN and outgoing_mail_available()) def can_reset_password(user): diff --git a/src/coulobre/hosting/templates/hosting/feature_configuration.html b/src/coulobre/hosting/templates/hosting/feature_configuration.html index 82a5968..1c8684f 100644 --- a/src/coulobre/hosting/templates/hosting/feature_configuration.html +++ b/src/coulobre/hosting/templates/hosting/feature_configuration.html @@ -10,6 +10,10 @@ {% endblock %} {% block page_content %} {% if selected_section == 'email' %} +
+

Outgoing panel email

+ Configure or test delivery +

Welcome email sender

Edit sender diff --git a/src/coulobre/hosting/templates/hosting/manage_invitation.html b/src/coulobre/hosting/templates/hosting/manage_invitation.html index b0d9167..ecb8c32 100644 --- a/src/coulobre/hosting/templates/hosting/manage_invitation.html +++ b/src/coulobre/hosting/templates/hosting/manage_invitation.html @@ -5,6 +5,11 @@

{{ login_user.get_username }}

{% if invitation %}

Invitation delivery · {{ invitation.get_delivery_display }}

{% endif %} + {% if delivery_blocker %} +

{{ delivery_blocker }} + {% if can_configure_delivery %}Outgoing panel email{% endif %} +

+ {% endif %}
{% csrf_token %} {{ form.as_div }} diff --git a/src/coulobre/hosting/templates/hosting/panel_mail_settings.html b/src/coulobre/hosting/templates/hosting/panel_mail_settings.html new file mode 100644 index 0000000..2ac8397 --- /dev/null +++ b/src/coulobre/hosting/templates/hosting/panel_mail_settings.html @@ -0,0 +1,41 @@ +{% extends "hosting/workspace_page.html" %} +{% block title %}Outgoing panel email · Coulobre Panel{% endblock %} +{% block page_title %}Outgoing panel email{% endblock %} +{% block page_context %} + ← Email settings +{% endblock %} +{% block page_content %} +
+

Transport

+ {% if relay %} +

SMTP relay configured. Sender: {{ sender }}.

+ {% if relay.tested_at %}

Last accepted test: {{ relay.tested_at }}.

{% endif %} + {% elif installed %} +

Using the installed transport. Sender: {{ sender }}.

+ {% else %} +

No outgoing transport is configured.

+ {% endif %} + + {% csrf_token %} +

Use an authenticated STARTTLS relay. You can use the shared Coulobre mail node or another SMTP provider. Saving applies only to this panel.

+ {{ form.as_div }} +
+ + {% if relay %} +
+ {% csrf_token %} + +
+ {% endif %} +
+ {% if relay or installed %} +
+

Test delivery

+
+ {% csrf_token %} + {{ test_form.as_div }} +
+
+
+ {% endif %} +{% endblock %} diff --git a/src/coulobre/hosting/test_panel_mail.py b/src/coulobre/hosting/test_panel_mail.py new file mode 100644 index 0000000..8fe0437 --- /dev/null +++ b/src/coulobre/hosting/test_panel_mail.py @@ -0,0 +1,84 @@ +from unittest.mock import patch + +from django.contrib.auth import get_user_model +from django.core.mail import EmailMessage +from django.test import TestCase, override_settings +from django.urls import reverse +from django_otp.plugins.otp_totp.models import TOTPDevice + +from .models import PanelMailRelay +from .panel_mail import PanelEmailBackend, outgoing_mail_available + + +@override_settings(EMAIL_HOST="", DEFAULT_FROM_EMAIL="panel@localhost") +class PanelMailRelayTests(TestCase): + @classmethod + def setUpTestData(cls): + cls.operator = get_user_model().objects.create_superuser("operator") + cls.device = TOTPDevice.objects.create(user=cls.operator, name="Panel") + + def sign_in(self): + self.client.force_login(self.operator) + session = self.client.session + session["otp_device_id"] = self.device.persistent_id + session.save() + + def save(self): + return self.client.post( + reverse("panel:panel_mail_settings"), + { + "host": "submission.example.net", + "port": "587", + "username": "panel-web1", + "password": "test-secret-value", + "sender": "panel@example.net", + }, + ) + + def test_requires_verified_superuser(self): + self.client.force_login(self.operator) + self.assertEqual(self.save().status_code, 403) + self.assertFalse(outgoing_mail_available()) + + def test_saved_relay_is_encrypted_and_used_for_default_sender(self): + self.sign_in() + self.assertEqual(self.save().status_code, 302) + relay = PanelMailRelay.objects.get() + self.assertNotIn("test-secret-value", relay.sealed_password) + self.assertTrue(outgoing_mail_available()) + page = self.client.get(reverse("panel:panel_mail_settings")) + self.assertNotContains(page, "test-secret-value") + self.assertContains(page, "submission.example.net") + backend = PanelEmailBackend() + self.assertEqual(backend.host, "submission.example.net") + self.assertEqual(backend.password, "test-secret-value") + self.assertTrue(backend.use_tls) + self.assertFalse(backend.use_ssl) + message = EmailMessage("Test", "Test", to=["reader@example.net"]) + with patch( + "django.core.mail.backends.smtp.EmailBackend.send_messages", + return_value=1, + ): + self.assertEqual(backend.send_messages([message]), 1) + self.assertEqual(message.from_email, "panel@example.net") + + def test_test_delivery_is_explicit_and_reset_restores_installed_transport( + self, + ): + self.sign_in() + path = reverse("panel:panel_mail_settings") + with patch( + "coulobre.hosting.panel_mail_views.send_mail", return_value=1 + ) as send: + self.save() + send.assert_not_called() + self.assertEqual( + self.client.post( + path, {"test_relay": "1", "recipient": "test@example.net"} + ).status_code, + 302, + ) + self.assertEqual(send.call_args.args[-1], ["test@example.net"]) + self.assertIsNotNone(PanelMailRelay.objects.get().tested_at) + self.client.post(path, {"reset_relay": "1"}) + self.assertFalse(outgoing_mail_available()) diff --git a/src/coulobre/hosting/urls.py b/src/coulobre/hosting/urls.py index ec258ec..c5f80d0 100644 --- a/src/coulobre/hosting/urls.py +++ b/src/coulobre/hosting/urls.py @@ -78,6 +78,7 @@ from .panel_content import ( preview_stylesheet, user_stylesheet, ) +from .panel_mail_views import PanelMailView from .panel_roles import AssignPanelRoleView, switch_panel_role from .password_reset import ( CustomerPasswordResetView, @@ -351,6 +352,11 @@ urlpatterns = [ FeatureConfigurationView.as_view(), name="operator_settings", ), + path( + "settings/email/transport/", + PanelMailView.as_view(), + name="panel_mail_settings", + ), path( "settings/email/sender/", InvitationMailSettingsView.as_view(), diff --git a/src/coulobre/hosting/workspaces.py b/src/coulobre/hosting/workspaces.py index 5a30302..b18359b 100644 --- a/src/coulobre/hosting/workspaces.py +++ b/src/coulobre/hosting/workspaces.py @@ -81,7 +81,8 @@ WORKSPACE_PARENT_ROUTES = { "remote_deploy": ("connected_nodes", ()), "dns_topology": ("dns_defaults", ()), "operator_settings": ("operator_settings", ("general",)), - "invitation_mail_settings": ("operator_settings", ("general",)), + "invitation_mail_settings": ("operator_settings", ("email",)), + "panel_mail_settings": ("operator_settings", ("email",)), "http_defaults": ("http_defaults", ("apache",)), "server_updates": ("updates", ()), "coulobre_package_updates": ("updates", ()), diff --git a/src/coulobre/settings.py b/src/coulobre/settings.py index 9335296..a8fe510 100644 --- a/src/coulobre/settings.py +++ b/src/coulobre/settings.py @@ -214,6 +214,7 @@ EMAIL_HOST_USER = os.environ.get("COULOBRE_SMTP_USER", "") EMAIL_HOST_PASSWORD = os.environ.get("COULOBRE_SMTP_PASSWORD", "") EMAIL_USE_TLS = os.environ.get("COULOBRE_SMTP_STARTTLS", "1") == "1" EMAIL_TIMEOUT = 10 +EMAIL_BACKEND = "coulobre.hosting.panel_mail.PanelEmailBackend" DEFAULT_FROM_EMAIL = os.environ.get( "COULOBRE_EMAIL_FROM", "Coulobre Panel " ) @@ -448,7 +449,7 @@ CELERY_BEAT_SCHEDULE = { "options": {"expires": 5.0}, }, } -if EMAIL_HOST and PASSWORD_RESET_ORIGIN: +if PASSWORD_RESET_ORIGIN: CELERY_BEAT_SCHEDULE["deliver-panel-notifications"] = { "task": "coulobre.hosting.tasks.deliver_panel_notifications", "schedule": 60.0, diff --git a/tests/test_cluster_installer.py b/tests/test_cluster_installer.py index 0757356..357b784 100644 --- a/tests/test_cluster_installer.py +++ b/tests/test_cluster_installer.py @@ -312,6 +312,7 @@ class ClusterInstallerTests(unittest.TestCase): "", "", "", + "later", "two", "192.0.2.22", "", @@ -325,6 +326,7 @@ class ClusterInstallerTests(unittest.TestCase): "", "", "", + "later", "cancel", ] output = StringIO()