Route mail domain aliases to the primary domain
This commit is contained in:
1 parent
ffa906fc12
commit
3c35a061d8
23 files changed
+929
-6
No files matched your search
@@ -125,6 +125,11 @@ def configure_mail(target, modern):
|
|||||||
dovecot = engine.group("dovecot")
|
dovecot = engine.group("dovecot")
|
||||||
ensure_table(Path("/etc/postfix/coulobre-domains"), mode=0o644)
|
ensure_table(Path("/etc/postfix/coulobre-domains"), mode=0o644)
|
||||||
ensure_table(Path("/etc/postfix/coulobre-mailboxes"), mode=0o644)
|
ensure_table(Path("/etc/postfix/coulobre-mailboxes"), mode=0o644)
|
||||||
|
aliases = Path("/etc/postfix/coulobre-aliases")
|
||||||
|
if not os.path.lexists(aliases):
|
||||||
|
engine.put_file(aliases, "# Managed by Coulobre Panel\n", mode=0o644)
|
||||||
|
else:
|
||||||
|
engine.root_file(aliases, 0o644)
|
||||||
ensure_table(
|
ensure_table(
|
||||||
Path("/etc/dovecot/coulobre-users"), mode=0o640, group=dovecot.gr_gid
|
Path("/etc/dovecot/coulobre-users"), mode=0o640, group=dovecot.gr_gid
|
||||||
)
|
)
|
||||||
@@ -139,6 +144,8 @@ def configure_mail(target, modern):
|
|||||||
"virtual_mailbox_maps": (
|
"virtual_mailbox_maps": (
|
||||||
"proxy:texthash:/etc/postfix/coulobre-mailboxes"
|
"proxy:texthash:/etc/postfix/coulobre-mailboxes"
|
||||||
),
|
),
|
||||||
|
"virtual_alias_maps": f"proxy:texthash:{aliases}",
|
||||||
|
"virtual_alias_domains": f"proxy:texthash:{aliases}",
|
||||||
"virtual_transport": "lmtp:unix:private/dovecot-lmtp",
|
"virtual_transport": "lmtp:unix:private/dovecot-lmtp",
|
||||||
"smtpd_reject_unlisted_recipient": "yes",
|
"smtpd_reject_unlisted_recipient": "yes",
|
||||||
"smtpd_tls_security_level": "may",
|
"smtpd_tls_security_level": "may",
|
||||||
@@ -149,6 +156,8 @@ def configure_mail(target, modern):
|
|||||||
managed_maps = (
|
managed_maps = (
|
||||||
"virtual_mailbox_domains",
|
"virtual_mailbox_domains",
|
||||||
"virtual_mailbox_maps",
|
"virtual_mailbox_maps",
|
||||||
|
"virtual_alias_maps",
|
||||||
|
"virtual_alias_domains",
|
||||||
"virtual_transport",
|
"virtual_transport",
|
||||||
)
|
)
|
||||||
for field in managed_maps:
|
for field in managed_maps:
|
||||||
|
|||||||
@@ -2627,6 +2627,33 @@ delivery status notification and the mail node's logs. Verify forwarding
|
|||||||
to external providers with real test mail because their SPF and DMARC
|
to external providers with real test mail because their SPF and DMARC
|
||||||
policies can affect delivery. [Postfix virtual aliases](https://www.postfix.org/virtual.5.html)
|
policies can affect delivery. [Postfix virtual aliases](https://www.postfix.org/virtual.5.html)
|
||||||
|
|
||||||
|
### Receive mail for another domain without separate mailboxes
|
||||||
|
|
||||||
|
Open the alias domain under **Domains** and choose **Manage mail alias**.
|
||||||
|
An operator can also use **Mail domain aliases** on the hosting account's
|
||||||
|
**Email** tab. Select a primary domain with a configured mailbox. The two
|
||||||
|
domains can be on separate hosting accounts on the same panel if they
|
||||||
|
belong to the same customer. On a shared mail node, the panel's receiver
|
||||||
|
key must cover both domains before adding or removing the alias.
|
||||||
|
|
||||||
|
Addresses at the alias domain follow the primary domain's matching mailbox
|
||||||
|
or forwarder. Unknown addresses are rejected unless the primary domain
|
||||||
|
has a catch-all. The alias does not add a mailbox, login, sending identity,
|
||||||
|
or additional quota. Coulobre adds the MX record to a managed DNS zone if
|
||||||
|
there is no conflicting mail route. For external DNS, copy the MX record
|
||||||
|
from the panel after the alias is active. Review existing routes before
|
||||||
|
switching providers and remove manually added MX records before removing
|
||||||
|
an alias.
|
||||||
|
|
||||||
|
New installer-managed mail nodes configure the Postfix maps for aliases.
|
||||||
|
Existing installations can reuse the managed map above. For domain aliases,
|
||||||
|
set both `virtual_alias_maps` and `virtual_alias_domains` to
|
||||||
|
`proxy:texthash:/etc/postfix/coulobre-aliases`. The latter may already
|
||||||
|
resolve to that map through Postfix's default. Check the effective settings
|
||||||
|
with `postconf -hx` and validate and reload Postfix after changing them.
|
||||||
|
Domain aliases are not enabled against custom alias tables, so Coulobre
|
||||||
|
cannot take over an address owned by an existing router.
|
||||||
|
|
||||||
### Enable scheduled automatic replies
|
### Enable scheduled automatic replies
|
||||||
|
|
||||||
Install the distribution's `dovecot-sieve` package. Add the settings in
|
Install the distribution's `dovecot-sieve` package. Add the settings in
|
||||||
|
|||||||
@@ -214,6 +214,8 @@ def record_action(retirement, actor, action, *, failures=None):
|
|||||||
|
|
||||||
@transaction.atomic
|
@transaction.atomic
|
||||||
def request_retirement(account_id, policy, confirmation, digest, actor):
|
def request_retirement(account_id, policy, confirmation, digest, actor):
|
||||||
|
from .mail_domain_aliases import account_aliases
|
||||||
|
|
||||||
account = lock_hosting_account(account_id, customer_id=None)
|
account = lock_hosting_account(account_id, customer_id=None)
|
||||||
retirement = getattr(account, "retirement", None)
|
retirement = getattr(account, "retirement", None)
|
||||||
if retirement is not None and retirement.policy == Policy.RELEASE:
|
if retirement is not None and retirement.policy == Policy.RELEASE:
|
||||||
@@ -237,6 +239,10 @@ def request_retirement(account_id, policy, confirmation, digest, actor):
|
|||||||
raise ValidationError(
|
raise ValidationError(
|
||||||
"Remove folder SFTP logins before retiring the hosting account."
|
"Remove folder SFTP logins before retiring the hosting account."
|
||||||
)
|
)
|
||||||
|
if account_aliases(account).exists():
|
||||||
|
raise ValidationError(
|
||||||
|
"Remove mail domain aliases before retiring the hosting account."
|
||||||
|
)
|
||||||
if account.mailbox_removals.filter(mailbox__isnull=False).exists():
|
if account.mailbox_removals.filter(mailbox__isnull=False).exists():
|
||||||
raise ValidationError(
|
raise ValidationError(
|
||||||
"Finish the mailbox removal before retiring the account."
|
"Finish the mailbox removal before retiring the account."
|
||||||
|
|||||||
@@ -80,11 +80,22 @@ def allowed_domains(account):
|
|||||||
|
|
||||||
@transaction.atomic
|
@transaction.atomic
|
||||||
def save_domain_policy(account_id, domain, customer_id, choices):
|
def save_domain_policy(account_id, domain, customer_id, choices):
|
||||||
|
from .mail_domain_aliases import account_aliases
|
||||||
|
|
||||||
account = lock_hosting_account(account_id, customer_id=customer_id)
|
account = lock_hosting_account(account_id, customer_id=customer_id)
|
||||||
require_open_account(account)
|
require_open_account(account)
|
||||||
if domain not in allowed_domains(account):
|
if domain not in allowed_domains(account):
|
||||||
raise Http404
|
raise Http404
|
||||||
previous = policy_for(account, domain)
|
previous = policy_for(account, domain)
|
||||||
|
if (
|
||||||
|
not choices["mail_managed"]
|
||||||
|
and account_aliases(account)
|
||||||
|
.filter(primary__account=account, primary__domain=domain)
|
||||||
|
.exists()
|
||||||
|
):
|
||||||
|
raise ValidationError(
|
||||||
|
"Remove mail domain aliases before switching providers."
|
||||||
|
)
|
||||||
if (
|
if (
|
||||||
previous.mail_managed
|
previous.mail_managed
|
||||||
and not choices["mail_managed"]
|
and not choices["mail_managed"]
|
||||||
@@ -221,6 +232,7 @@ def domain_workspace(request, pk, page):
|
|||||||
"forwarders": "Forwarders",
|
"forwarders": "Forwarders",
|
||||||
"replies": "Automatic replies",
|
"replies": "Automatic replies",
|
||||||
}
|
}
|
||||||
|
from .mail_domain_alias_views import may_manage_aliases
|
||||||
from .mail_policies import mail_policy_available
|
from .mail_policies import mail_policy_available
|
||||||
from .mailbox_removal import can_remove_mailbox
|
from .mailbox_removal import can_remove_mailbox
|
||||||
from .roundcube import roundcube_available
|
from .roundcube import roundcube_available
|
||||||
@@ -241,6 +253,8 @@ def domain_workspace(request, pk, page):
|
|||||||
"domain": domain,
|
"domain": domain,
|
||||||
"form": form,
|
"form": form,
|
||||||
"policy": policy,
|
"policy": policy,
|
||||||
|
"can_manage_mail_alias": may_manage_aliases(request)
|
||||||
|
and account.website_domains.filter(domain=domain).exists(),
|
||||||
"zone": zone,
|
"zone": zone,
|
||||||
"records": zone_record_rows(zone.spec) if zone else (),
|
"records": zone_record_rows(zone.spec) if zone else (),
|
||||||
"external_website_records": website_records(
|
"external_website_records": website_records(
|
||||||
|
|||||||
@@ -0,0 +1,110 @@
|
|||||||
|
from django import forms
|
||||||
|
from django.conf import settings
|
||||||
|
from django.core.exceptions import PermissionDenied, ValidationError
|
||||||
|
from django.http import Http404
|
||||||
|
from django.shortcuts import get_object_or_404, redirect, render
|
||||||
|
from django.urls import reverse
|
||||||
|
from django.views.decorators.cache import never_cache
|
||||||
|
from django.views.decorators.http import require_http_methods
|
||||||
|
|
||||||
|
from .access import can_manage_hosting, customer_for_user
|
||||||
|
from .mail_domain_aliases import (
|
||||||
|
aliases_available,
|
||||||
|
queue_domain_alias,
|
||||||
|
remove_domain_alias,
|
||||||
|
)
|
||||||
|
from .models import HostingMailDomain, WebsiteDomain
|
||||||
|
|
||||||
|
PERMISSIONS = (
|
||||||
|
"hosting.view_hostingaccount",
|
||||||
|
"hosting.change_hostingmaildomain",
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def may_manage_aliases(request):
|
||||||
|
return (
|
||||||
|
aliases_available()
|
||||||
|
and not getattr(request, "impersonation", None)
|
||||||
|
and can_manage_hosting(request.user, PERMISSIONS)
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
class MailDomainAliasForm(forms.Form):
|
||||||
|
primary = forms.ModelChoiceField(
|
||||||
|
label="Primary mail domain", queryset=HostingMailDomain.objects.none()
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@never_cache
|
||||||
|
@require_http_methods(("GET", "HEAD", "POST"))
|
||||||
|
def mail_domain_alias(request, pk, domain):
|
||||||
|
if not aliases_available():
|
||||||
|
raise Http404
|
||||||
|
if not may_manage_aliases(request):
|
||||||
|
raise PermissionDenied
|
||||||
|
customer = customer_for_user(request.user)
|
||||||
|
claims = WebsiteDomain.objects.select_related("account")
|
||||||
|
if customer is not None:
|
||||||
|
claims = claims.filter(account__customer=customer)
|
||||||
|
reservation = get_object_or_404(
|
||||||
|
claims, account=pk, domain=domain, account__retired_at__isnull=True
|
||||||
|
)
|
||||||
|
targets = HostingMailDomain.objects.filter(
|
||||||
|
account__retired_at__isnull=True,
|
||||||
|
mailboxes__provisioning__finished_at__isnull=False,
|
||||||
|
mailboxes__provisioning__problem="",
|
||||||
|
mailboxes__removal__isnull=True,
|
||||||
|
).exclude(domain=domain)
|
||||||
|
if reservation.account.customer_id:
|
||||||
|
targets = targets.filter(
|
||||||
|
account__customer_id=reservation.account.customer_id
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
targets = targets.filter(account=reservation.account)
|
||||||
|
job = getattr(reservation, "mail_alias", None)
|
||||||
|
data = request.POST if request.method == "POST" else None
|
||||||
|
form = MailDomainAliasForm(
|
||||||
|
data, initial={"primary": job.primary_id} if job else {}
|
||||||
|
)
|
||||||
|
form.fields["primary"].queryset = targets.order_by("domain").distinct()
|
||||||
|
problem = ""
|
||||||
|
if request.method == "POST":
|
||||||
|
try:
|
||||||
|
action = request.POST.get("action")
|
||||||
|
if action == "remove" and job is not None:
|
||||||
|
remove_domain_alias(job, customer)
|
||||||
|
elif action == "save":
|
||||||
|
if form.is_valid():
|
||||||
|
queue_domain_alias(
|
||||||
|
reservation, form.cleaned_data["primary"], customer
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
action = None
|
||||||
|
else:
|
||||||
|
raise Http404
|
||||||
|
except ValidationError as error:
|
||||||
|
problem = " ".join(error.messages)
|
||||||
|
else:
|
||||||
|
if action is not None:
|
||||||
|
return redirect(request.path)
|
||||||
|
backlink = (
|
||||||
|
reverse(
|
||||||
|
"panel:domain_workspace",
|
||||||
|
args=[pk, "domains"],
|
||||||
|
query={"domain": domain},
|
||||||
|
)
|
||||||
|
if customer
|
||||||
|
else reservation.account.get_absolute_url()
|
||||||
|
)
|
||||||
|
return render(
|
||||||
|
request,
|
||||||
|
"hosting/mail_domain_alias_form.html",
|
||||||
|
{
|
||||||
|
"domain": domain,
|
||||||
|
"job": job,
|
||||||
|
"form": form,
|
||||||
|
"problem": problem,
|
||||||
|
"backlink": backlink,
|
||||||
|
"exchange": settings.MAIL_MX_HOST,
|
||||||
|
},
|
||||||
|
)
|
||||||
@@ -0,0 +1,194 @@
|
|||||||
|
from dataclasses import replace
|
||||||
|
|
||||||
|
from django.conf import settings
|
||||||
|
from django.core.exceptions import ValidationError
|
||||||
|
from django.db import transaction
|
||||||
|
from django.db.models import Q
|
||||||
|
|
||||||
|
from coulobre.dns_node import MAX_SOA_SERIAL, MxRecord
|
||||||
|
|
||||||
|
from .dns_publication import queue_zone_snapshot
|
||||||
|
from .domain_policies import policy_for, require_managed
|
||||||
|
from .mail_dns_setup import closest_zone
|
||||||
|
from .models import (
|
||||||
|
HostingAccount,
|
||||||
|
HostingDnsZone,
|
||||||
|
HostingMailDomain,
|
||||||
|
MailDomainAlias,
|
||||||
|
WebsiteAlias,
|
||||||
|
WebsiteDomain,
|
||||||
|
)
|
||||||
|
from .node_client import apply_on_local_node
|
||||||
|
from .resource_requests import require_active_services
|
||||||
|
|
||||||
|
|
||||||
|
def aliases_available():
|
||||||
|
return settings.LOCAL_MAILBOX_PROVISIONING and bool(settings.MAIL_MX_HOST)
|
||||||
|
|
||||||
|
|
||||||
|
def account_aliases(account):
|
||||||
|
return MailDomainAlias.objects.filter(
|
||||||
|
Q(reservation__account=account) | Q(primary__account=account)
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def owned_with(source, target):
|
||||||
|
return source.pk == target.pk or (
|
||||||
|
source.customer_id is not None
|
||||||
|
and source.customer_id == target.customer_id
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def mesh_accounts(source_id, target_id):
|
||||||
|
accounts = {
|
||||||
|
account.pk: account
|
||||||
|
for account in HostingAccount.objects.select_for_update()
|
||||||
|
.filter(pk__in=(source_id, target_id))
|
||||||
|
.order_by("pk")
|
||||||
|
}
|
||||||
|
return accounts[source_id], accounts[target_id]
|
||||||
|
|
||||||
|
|
||||||
|
def validate_alias(reservation, primary, source, target):
|
||||||
|
require_active_services(source)
|
||||||
|
require_active_services(target)
|
||||||
|
if not owned_with(source, target):
|
||||||
|
raise ValidationError("Both domains must belong to the same customer.")
|
||||||
|
if reservation.domain == primary.domain:
|
||||||
|
raise ValidationError("Choose a different primary mail domain.")
|
||||||
|
if WebsiteAlias.objects.filter(
|
||||||
|
reservation=reservation, operation=WebsiteAlias.Operation.REMOVE
|
||||||
|
).exists():
|
||||||
|
raise ValidationError("This domain is being removed.")
|
||||||
|
require_managed(target, primary.domain, "mail_managed")
|
||||||
|
if HostingMailDomain.objects.filter(domain=reservation.domain).exists():
|
||||||
|
raise ValidationError(
|
||||||
|
"The alias already has an independent mail domain."
|
||||||
|
)
|
||||||
|
if not primary.mailboxes.filter(
|
||||||
|
provisioning__finished_at__isnull=False,
|
||||||
|
provisioning__problem="",
|
||||||
|
removal__isnull=True,
|
||||||
|
).exists():
|
||||||
|
raise ValidationError("Provision a primary mailbox first.")
|
||||||
|
|
||||||
|
|
||||||
|
@transaction.atomic
|
||||||
|
def queue_domain_alias(reservation, primary, customer):
|
||||||
|
source, target = mesh_accounts(reservation.account_id, primary.account_id)
|
||||||
|
if customer is not None and source.customer_id != customer.pk:
|
||||||
|
raise ValidationError("This domain is not assigned to you.")
|
||||||
|
reservation = WebsiteDomain.objects.select_for_update().get(
|
||||||
|
pk=reservation.pk
|
||||||
|
)
|
||||||
|
if not aliases_available():
|
||||||
|
raise ValidationError("Configure managed email and its MX host first.")
|
||||||
|
validate_alias(reservation, primary, source, target)
|
||||||
|
dns_change(source, reservation.domain, settings.MAIL_MX_HOST)
|
||||||
|
job = MailDomainAlias.objects.filter(reservation=reservation).first()
|
||||||
|
if job is None:
|
||||||
|
return MailDomainAlias.objects.create(
|
||||||
|
reservation=reservation, primary=primary
|
||||||
|
)
|
||||||
|
if job.primary_id != primary.pk or job.remove or not job.problem:
|
||||||
|
raise ValidationError("Remove the current alias before changing it.")
|
||||||
|
MailDomainAlias.objects.requeue(MailDomainAlias.objects.filter(pk=job.pk))
|
||||||
|
return job
|
||||||
|
|
||||||
|
|
||||||
|
@transaction.atomic
|
||||||
|
def remove_domain_alias(job, customer):
|
||||||
|
source, _ = mesh_accounts(
|
||||||
|
job.reservation.account_id, job.primary.account_id
|
||||||
|
)
|
||||||
|
if customer is not None and source.customer_id != customer.pk:
|
||||||
|
raise ValidationError("This domain is not assigned to you.")
|
||||||
|
if not MailDomainAlias.objects.requeue(
|
||||||
|
MailDomainAlias.objects.filter(pk=job.pk), remove=True
|
||||||
|
):
|
||||||
|
raise ValidationError("Wait for the current change to finish.")
|
||||||
|
|
||||||
|
|
||||||
|
def dns_change(account, domain, exchange, *, remove=False):
|
||||||
|
if not settings.LOCAL_DNS_PUBLISHING:
|
||||||
|
return None, None
|
||||||
|
zone = closest_zone(HostingDnsZone.objects.all(), domain)
|
||||||
|
if (
|
||||||
|
zone is None
|
||||||
|
or zone.account_id != account.pk
|
||||||
|
or not policy_for(account, zone.domain).dns_managed
|
||||||
|
):
|
||||||
|
return None, None
|
||||||
|
zone = HostingDnsZone.objects.select_for_update().get(pk=zone.pk)
|
||||||
|
spec = zone.spec
|
||||||
|
mx = MxRecord(domain, 10, exchange)
|
||||||
|
existing = tuple(
|
||||||
|
record for record in spec.mx_records if record.name == domain
|
||||||
|
)
|
||||||
|
if remove:
|
||||||
|
if mx not in existing:
|
||||||
|
return None, None
|
||||||
|
records = tuple(item for item in spec.mx_records if item != mx)
|
||||||
|
else:
|
||||||
|
if existing:
|
||||||
|
if any(record.exchange != mx.exchange for record in existing):
|
||||||
|
raise ValidationError(
|
||||||
|
"Review the existing MX targets in the DNS editor first."
|
||||||
|
)
|
||||||
|
return None, None
|
||||||
|
records = (*spec.mx_records, mx)
|
||||||
|
publication = getattr(zone, "publication", None)
|
||||||
|
if publication and (
|
||||||
|
publication.finished_at is None or publication.serial != zone.serial
|
||||||
|
):
|
||||||
|
raise ValidationError("Finish the current DNS publication first.")
|
||||||
|
revision = replace(
|
||||||
|
spec,
|
||||||
|
serial=(spec.serial + 1) % (MAX_SOA_SERIAL + 1),
|
||||||
|
mx_records=records,
|
||||||
|
)
|
||||||
|
return zone, revision
|
||||||
|
|
||||||
|
|
||||||
|
@transaction.atomic
|
||||||
|
def apply_domain_alias(job):
|
||||||
|
source, target = mesh_accounts(
|
||||||
|
job.reservation.account_id, job.primary.account_id
|
||||||
|
)
|
||||||
|
try:
|
||||||
|
if job.remove:
|
||||||
|
change = (
|
||||||
|
dns_change(
|
||||||
|
source, job.spec.domain, job.mx_exchange, remove=True
|
||||||
|
)
|
||||||
|
if job.mx_exchange
|
||||||
|
else (None, None)
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
validate_alias(job.reservation, job.primary, source, target)
|
||||||
|
change = dns_change(source, job.spec.domain, settings.MAIL_MX_HOST)
|
||||||
|
except ValidationError as error:
|
||||||
|
raise ValueError(" ".join(error.messages)) from None
|
||||||
|
apply_on_local_node(
|
||||||
|
job.spec,
|
||||||
|
"/run/coulobre-mail-apply.sock",
|
||||||
|
"mail node",
|
||||||
|
"mail domain alias",
|
||||||
|
identity=job.spec.identity(),
|
||||||
|
)
|
||||||
|
zone, revision = change
|
||||||
|
if zone is not None:
|
||||||
|
zone.serial = revision.serial
|
||||||
|
zone.mx_records = revision.manifest().get("mx_records", [])
|
||||||
|
zone.save(update_fields=["serial", "mx_records"])
|
||||||
|
queue_zone_snapshot(zone)
|
||||||
|
return {
|
||||||
|
"active": not job.remove,
|
||||||
|
"mx_exchange": (
|
||||||
|
""
|
||||||
|
if job.remove
|
||||||
|
else settings.MAIL_MX_HOST
|
||||||
|
if zone
|
||||||
|
else job.mx_exchange
|
||||||
|
),
|
||||||
|
}
|
||||||
@@ -0,0 +1,61 @@
|
|||||||
|
# Generated by Django 5.2.19 on 2026-12-02 12:08
|
||||||
|
|
||||||
|
import django.db.models.deletion
|
||||||
|
import django.utils.timezone
|
||||||
|
from django.db import migrations, models
|
||||||
|
|
||||||
|
|
||||||
|
class Migration(migrations.Migration):
|
||||||
|
dependencies = [
|
||||||
|
("hosting", "0089_wordpress_update_recovery"),
|
||||||
|
]
|
||||||
|
|
||||||
|
operations = [
|
||||||
|
migrations.CreateModel(
|
||||||
|
name="MailDomainAlias",
|
||||||
|
fields=[
|
||||||
|
(
|
||||||
|
"id",
|
||||||
|
models.BigAutoField(
|
||||||
|
auto_created=True,
|
||||||
|
primary_key=True,
|
||||||
|
serialize=False,
|
||||||
|
verbose_name="ID",
|
||||||
|
),
|
||||||
|
),
|
||||||
|
(
|
||||||
|
"requested_at",
|
||||||
|
models.DateTimeField(default=django.utils.timezone.now),
|
||||||
|
),
|
||||||
|
(
|
||||||
|
"last_dispatched_at",
|
||||||
|
models.DateTimeField(blank=True, null=True),
|
||||||
|
),
|
||||||
|
("started_at", models.DateTimeField(blank=True, null=True)),
|
||||||
|
("finished_at", models.DateTimeField(blank=True, null=True)),
|
||||||
|
("problem", models.TextField(blank=True)),
|
||||||
|
("remove", models.BooleanField(default=False)),
|
||||||
|
("active", models.BooleanField(default=False)),
|
||||||
|
("mx_exchange", models.CharField(blank=True, max_length=253)),
|
||||||
|
(
|
||||||
|
"primary",
|
||||||
|
models.ForeignKey(
|
||||||
|
on_delete=django.db.models.deletion.PROTECT,
|
||||||
|
related_name="aliases",
|
||||||
|
to="hosting.hostingmaildomain",
|
||||||
|
),
|
||||||
|
),
|
||||||
|
(
|
||||||
|
"reservation",
|
||||||
|
models.OneToOneField(
|
||||||
|
on_delete=django.db.models.deletion.PROTECT,
|
||||||
|
related_name="mail_alias",
|
||||||
|
to="hosting.websitedomain",
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
options={
|
||||||
|
"abstract": False,
|
||||||
|
},
|
||||||
|
),
|
||||||
|
]
|
||||||
@@ -1667,6 +1667,26 @@ class MailPolicyPublication(ProvisioningJob):
|
|||||||
abstract = True
|
abstract = True
|
||||||
|
|
||||||
|
|
||||||
|
class MailDomainAlias(ProvisioningJob):
|
||||||
|
reservation = models.OneToOneField(
|
||||||
|
WebsiteDomain, on_delete=models.PROTECT, related_name="mail_alias"
|
||||||
|
)
|
||||||
|
primary = models.ForeignKey(
|
||||||
|
HostingMailDomain, on_delete=models.PROTECT, related_name="aliases"
|
||||||
|
)
|
||||||
|
remove = models.BooleanField(default=False)
|
||||||
|
active = models.BooleanField(default=False)
|
||||||
|
mx_exchange = models.CharField(max_length=253, blank=True)
|
||||||
|
|
||||||
|
@property
|
||||||
|
def spec(self):
|
||||||
|
from coulobre.mail_domain_alias import MailDomainAliasRequest
|
||||||
|
|
||||||
|
return MailDomainAliasRequest(
|
||||||
|
self.reservation.domain, self.primary.domain, self.remove
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
class MailRoutingPublication(MailPolicyPublication):
|
class MailRoutingPublication(MailPolicyPublication):
|
||||||
mail_domain = models.OneToOneField(
|
mail_domain = models.OneToOneField(
|
||||||
HostingMailDomain, on_delete=models.CASCADE, related_name="routing"
|
HostingMailDomain, on_delete=models.CASCADE, related_name="routing"
|
||||||
|
|||||||
@@ -165,6 +165,14 @@ def save_operator_account(account, actor, *, changed_fields=None):
|
|||||||
require_open_account(previous)
|
require_open_account(previous)
|
||||||
if "primary_domain" in changed_fields:
|
if "primary_domain" in changed_fields:
|
||||||
require_active_services(previous)
|
require_active_services(previous)
|
||||||
|
if {"customer", "primary_domain"}.intersection(changed_fields):
|
||||||
|
from .mail_domain_aliases import account_aliases
|
||||||
|
|
||||||
|
if account_aliases(previous).exists():
|
||||||
|
raise ValidationError(
|
||||||
|
"Remove mail domain aliases before changing the "
|
||||||
|
"customer or primary domain."
|
||||||
|
)
|
||||||
if {"customer", "primary_domain"}.intersection(
|
if {"customer", "primary_domain"}.intersection(
|
||||||
changed_fields
|
changed_fields
|
||||||
) and previous.folder_sftp_logins.exists():
|
) and previous.folder_sftp_logins.exists():
|
||||||
|
|||||||
@@ -109,6 +109,12 @@ def create_mailbox_request(
|
|||||||
"This mail domain is outside the hosting account."
|
"This mail domain is outside the hosting account."
|
||||||
)
|
)
|
||||||
require_managed(account, domain, "mail_managed")
|
require_managed(account, domain, "mail_managed")
|
||||||
|
if account.website_domains.filter(
|
||||||
|
domain=domain, mail_alias__isnull=False
|
||||||
|
).exists():
|
||||||
|
raise ValidationError(
|
||||||
|
"Add mailboxes on the primary mail domain, not its alias."
|
||||||
|
)
|
||||||
try:
|
try:
|
||||||
spec = MailboxSpec(domain, local_part)
|
spec = MailboxSpec(domain, local_part)
|
||||||
except ValueError as error:
|
except ValueError as error:
|
||||||
|
|||||||
@@ -36,6 +36,7 @@ from .backup_restores import (
|
|||||||
from .backup_retention import plan_backup_expirations
|
from .backup_retention import plan_backup_expirations
|
||||||
from .independent_websites import active_websites, apply_website_operation
|
from .independent_websites import active_websites, apply_website_operation
|
||||||
from .mail_dns_setup import sync_mail_dns
|
from .mail_dns_setup import sync_mail_dns
|
||||||
|
from .mail_domain_aliases import aliases_available, apply_domain_alias
|
||||||
from .mail_policies import apply_policy, mail_policy_available
|
from .mail_policies import apply_policy, mail_policy_available
|
||||||
from .mailbox_removal import apply_removal
|
from .mailbox_removal import apply_removal
|
||||||
from .models import (
|
from .models import (
|
||||||
@@ -55,6 +56,7 @@ from .models import (
|
|||||||
MailboxProvisioning,
|
MailboxProvisioning,
|
||||||
MailboxRemoval,
|
MailboxRemoval,
|
||||||
MailDeliverySearch,
|
MailDeliverySearch,
|
||||||
|
MailDomainAlias,
|
||||||
MailFilterCheck,
|
MailFilterCheck,
|
||||||
MailRoutingPublication,
|
MailRoutingPublication,
|
||||||
MailVacationPublication,
|
MailVacationPublication,
|
||||||
@@ -359,6 +361,12 @@ def dispatch_mailbox_provisioning():
|
|||||||
publish_mail_routing,
|
publish_mail_routing,
|
||||||
MAILBOX_PROVISIONING_QUEUE,
|
MAILBOX_PROVISIONING_QUEUE,
|
||||||
)
|
)
|
||||||
|
if aliases_available():
|
||||||
|
dispatch_provisioning_jobs(
|
||||||
|
MailDomainAlias,
|
||||||
|
publish_mail_domain_alias,
|
||||||
|
MAILBOX_PROVISIONING_QUEUE,
|
||||||
|
)
|
||||||
if mail_policy_available("vacation"):
|
if mail_policy_available("vacation"):
|
||||||
dispatch_provisioning_jobs(
|
dispatch_provisioning_jobs(
|
||||||
MailVacationPublication,
|
MailVacationPublication,
|
||||||
@@ -882,6 +890,25 @@ def apply_mail_routing_job(job):
|
|||||||
return apply_policy(job, job.mail_domain)
|
return apply_policy(job, job.mail_domain)
|
||||||
|
|
||||||
|
|
||||||
|
@shared_task(acks_late=True, reject_on_worker_lost=True)
|
||||||
|
def publish_mail_domain_alias(job_id):
|
||||||
|
if aliases_available():
|
||||||
|
jobs = MailDomainAlias.objects.select_related("reservation", "primary")
|
||||||
|
run_provisioning_job(
|
||||||
|
jobs,
|
||||||
|
job_id,
|
||||||
|
apply_domain_alias,
|
||||||
|
"Could not reach the mail node. Check its connection and retry.",
|
||||||
|
)
|
||||||
|
jobs.filter(
|
||||||
|
pk=job_id,
|
||||||
|
remove=True,
|
||||||
|
active=False,
|
||||||
|
finished_at__isnull=False,
|
||||||
|
problem="",
|
||||||
|
).delete()
|
||||||
|
|
||||||
|
|
||||||
@shared_task(acks_late=True, reject_on_worker_lost=True)
|
@shared_task(acks_late=True, reject_on_worker_lost=True)
|
||||||
def publish_mail_vacation(job_id):
|
def publish_mail_vacation(job_id):
|
||||||
if mail_policy_available("vacation"):
|
if mail_policy_available("vacation"):
|
||||||
|
|||||||
@@ -278,6 +278,14 @@
|
|||||||
{% endif %}
|
{% endif %}
|
||||||
{% if is_tenant or perms.hosting.view_hostingmailbox %}
|
{% if is_tenant or perms.hosting.view_hostingmailbox %}
|
||||||
<section class="account-content" id="email" data-account-section tabindex="-1" aria-label="Email">
|
<section class="account-content" id="email" data-account-section tabindex="-1" aria-label="Email">
|
||||||
|
{% if mail_alias_domains %}
|
||||||
|
<section class="surface" aria-label="Mail domain aliases">
|
||||||
|
<header class="section-heading"><h2>Mail domain aliases</h2></header>
|
||||||
|
<ul class="workspace-list">{% for domain in mail_alias_domains %}
|
||||||
|
<li><a href="{% url 'panel:mail_domain_alias' account.pk domain.domain %}">{{ domain.domain }}</a>{% if domain.mail_alias %} → {{ domain.mail_alias.primary.domain }}{% endif %}</li>
|
||||||
|
{% endfor %}</ul>
|
||||||
|
</section>
|
||||||
|
{% endif %}
|
||||||
{% if mail_domains %}
|
{% if mail_domains %}
|
||||||
<section class="surface" aria-labelledby="mail-domains-heading">
|
<section class="surface" aria-labelledby="mail-domains-heading">
|
||||||
<header class="section-heading">
|
<header class="section-heading">
|
||||||
|
|||||||
@@ -12,6 +12,9 @@
|
|||||||
{% endblock %}
|
{% endblock %}
|
||||||
{% block page_content %}
|
{% block page_content %}
|
||||||
{% if page == 'domains' %}
|
{% if page == 'domains' %}
|
||||||
|
{% if can_manage_mail_alias %}
|
||||||
|
<section class="surface section-heading"><h2>Mail domain alias</h2><a class="button secondary" href="{% url 'panel:mail_domain_alias' account.pk domain %}">Manage mail alias</a></section>
|
||||||
|
{% endif %}
|
||||||
<section class="surface editor-surface" aria-label="Domain services">
|
<section class="surface editor-surface" aria-label="Domain services">
|
||||||
<form method="post" class="editor">{% csrf_token %}{{ form.as_div }}<button class="button primary" type="submit">Save service preferences</button></form>
|
<form method="post" class="editor">{% csrf_token %}{{ form.as_div }}<button class="button primary" type="submit">Save service preferences</button></form>
|
||||||
</section>
|
</section>
|
||||||
|
|||||||
@@ -0,0 +1,31 @@
|
|||||||
|
{% extends "hosting/workspace_page.html" %}
|
||||||
|
{% load static %}
|
||||||
|
{% block title %}Mail domain alias · Coulobre Panel{% endblock %}
|
||||||
|
{% block page_title %}Mail domain alias{% endblock %}
|
||||||
|
{% block page_metadata %}<p class="heading-meta">{{ domain }}</p>{% endblock %}
|
||||||
|
{% block page_actions %}<a href="{{ backlink }}">Back to hosting</a>{% endblock %}
|
||||||
|
{% block page_content %}
|
||||||
|
<section class="surface editor-surface">
|
||||||
|
<p>Deliver mail for this domain using the mailboxes, forwarders and catch-all of its primary mail domain. This does not add a mailbox or let you send from the alias.</p>
|
||||||
|
{% if job %}
|
||||||
|
<p><strong>Primary mail domain</strong> {{ job.primary.domain }}</p>
|
||||||
|
<p role="status">{% if job.remove %}Removal{% else %}Setup{% endif %} {{ job.state }}.</p>
|
||||||
|
{% if job.problem %}<p class="error" role="alert">{{ job.problem }}</p>{% endif %}
|
||||||
|
{% endif %}
|
||||||
|
{% if problem %}<p class="error" role="alert">{{ problem }}</p>{% endif %}
|
||||||
|
{% if not job or job.problem and not job.remove %}
|
||||||
|
<form method="post" class="editor">{% csrf_token %}{{ form.as_div }}<button class="button primary" name="action" value="save">{% if job %}Retry setup{% else %}Add mail alias{% endif %}</button></form>
|
||||||
|
{% endif %}
|
||||||
|
{% if job.finished_at %}
|
||||||
|
<form method="post" class="editor">{% csrf_token %}<button class="button secondary" name="action" value="remove">{% if job.remove %}Retry removal{% else %}Remove mail alias{% endif %}</button></form>
|
||||||
|
{% endif %}
|
||||||
|
{% if job.active %}
|
||||||
|
<h2>Incoming mail DNS</h2>
|
||||||
|
<p>For external DNS, review existing mail delivery before setting this record at your DNS provider. Remove it there if you stop using the alias.</p>
|
||||||
|
<textarea id="mail-alias-dns-record" rows="2" readonly aria-label="MX record">{{ domain }} MX 10 {{ exchange }}.</textarea>
|
||||||
|
<button type="button" class="button secondary" hidden data-copy-field="mail-alias-dns-record">Copy MX record</button>
|
||||||
|
<p id="copy-field-status" role="status"></p>
|
||||||
|
<script src="{% static 'hosting/copy-field.js' %}" defer></script>
|
||||||
|
{% endif %}
|
||||||
|
</section>
|
||||||
|
{% endblock %}
|
||||||
@@ -0,0 +1,160 @@
|
|||||||
|
from dataclasses import asdict
|
||||||
|
from unittest.mock import patch
|
||||||
|
|
||||||
|
from django.contrib.auth import get_user_model
|
||||||
|
from django.test import SimpleTestCase, TestCase, override_settings
|
||||||
|
from django.urls import reverse
|
||||||
|
from django.utils import timezone
|
||||||
|
|
||||||
|
from coulobre.dns_node import MxRecord
|
||||||
|
from coulobre.mail_domain_alias import MailDomainAliasRequest
|
||||||
|
from coulobre.mail_node_routing import publish_routes
|
||||||
|
from coulobre.mail_policy import MailRouting
|
||||||
|
|
||||||
|
from .models import (
|
||||||
|
Customer,
|
||||||
|
HostingAccount,
|
||||||
|
HostingDnsZone,
|
||||||
|
HostingMailbox,
|
||||||
|
HostingMailDomain,
|
||||||
|
MailboxProvisioning,
|
||||||
|
MailDomainAlias,
|
||||||
|
)
|
||||||
|
from .tasks import publish_mail_domain_alias
|
||||||
|
|
||||||
|
|
||||||
|
class RoutingTableTests(SimpleTestCase):
|
||||||
|
def test_primary_rules_define_exact_alias_recipients(self):
|
||||||
|
primary = "primary.example.test"
|
||||||
|
alias = "alias.example.test"
|
||||||
|
mailbox = f"info@{primary}"
|
||||||
|
forwarding = f"sales@{primary}"
|
||||||
|
with patch("coulobre.mail_node_apply.publish_table") as publish:
|
||||||
|
for catchall in ("", mailbox):
|
||||||
|
with self.subTest(catchall=catchall):
|
||||||
|
route = MailRouting(
|
||||||
|
primary, {"sales": [mailbox]}, catchall
|
||||||
|
)
|
||||||
|
publish_routes(
|
||||||
|
{primary: route},
|
||||||
|
{mailbox},
|
||||||
|
"",
|
||||||
|
aliases={alias: primary},
|
||||||
|
)
|
||||||
|
rows = publish.call_args.args[1][2]
|
||||||
|
expected = {
|
||||||
|
f"{alias} OK",
|
||||||
|
f"info@{alias} {mailbox}",
|
||||||
|
f"sales@{alias} {forwarding}",
|
||||||
|
}
|
||||||
|
if catchall:
|
||||||
|
expected.add(f"@{alias} {mailbox}")
|
||||||
|
self.assertEqual(
|
||||||
|
{row for row in rows if alias in row}, expected
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@override_settings(
|
||||||
|
LOCAL_MAILBOX_PROVISIONING=True,
|
||||||
|
LOCAL_DNS_PUBLISHING=True,
|
||||||
|
MAIL_MX_HOST="mx.example.test",
|
||||||
|
)
|
||||||
|
class MailDomainAliasTests(TestCase):
|
||||||
|
@classmethod
|
||||||
|
def setUpTestData(cls):
|
||||||
|
users = get_user_model().objects
|
||||||
|
cls.user = users.create_user("customer")
|
||||||
|
cls.customer = Customer.objects.create(user=cls.user)
|
||||||
|
cls.source = HostingAccount.objects.create(
|
||||||
|
name="Alias",
|
||||||
|
primary_domain="alias.example.test",
|
||||||
|
customer=cls.customer,
|
||||||
|
)
|
||||||
|
cls.owner = HostingAccount.objects.create(
|
||||||
|
name="Primary",
|
||||||
|
primary_domain="primary.example.test",
|
||||||
|
customer=cls.customer,
|
||||||
|
)
|
||||||
|
cls.primary = HostingMailDomain.objects.create(
|
||||||
|
account=cls.owner, domain=cls.owner.primary_domain
|
||||||
|
)
|
||||||
|
mailbox = HostingMailbox.objects.create(
|
||||||
|
mail_domain=cls.primary, local_part="info"
|
||||||
|
)
|
||||||
|
MailboxProvisioning.objects.create(
|
||||||
|
mailbox=mailbox, finished_at=timezone.now()
|
||||||
|
)
|
||||||
|
|
||||||
|
def setUp(self):
|
||||||
|
self.client.force_login(self.user)
|
||||||
|
self.url = reverse(
|
||||||
|
"panel:mail_domain_alias",
|
||||||
|
args=(self.source.pk, self.source.primary_domain),
|
||||||
|
)
|
||||||
|
|
||||||
|
def zone(self, mx_records=()):
|
||||||
|
return HostingDnsZone.objects.create(
|
||||||
|
account=self.source,
|
||||||
|
domain=self.source.primary_domain,
|
||||||
|
nameservers=["ns.example.test"],
|
||||||
|
responsible_name="hostmaster.example.test",
|
||||||
|
mx_records=[asdict(mx) for mx in mx_records],
|
||||||
|
)
|
||||||
|
|
||||||
|
def queue(self):
|
||||||
|
return self.client.post(
|
||||||
|
self.url, {"action": "save", "primary": self.primary.pk}
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_add_and_remove_without_creating_a_second_mailbox(self):
|
||||||
|
zone = self.zone()
|
||||||
|
self.assertRedirects(self.queue(), self.url)
|
||||||
|
job = MailDomainAlias.objects.get()
|
||||||
|
spec = MailDomainAliasRequest(
|
||||||
|
self.source.primary_domain, self.primary.domain
|
||||||
|
)
|
||||||
|
with patch(
|
||||||
|
"coulobre.hosting.mail_domain_aliases.apply_on_local_node"
|
||||||
|
) as apply:
|
||||||
|
publish_mail_domain_alias.run(job.pk)
|
||||||
|
self.assertEqual(apply.call_args.args[0], spec)
|
||||||
|
self.assertEqual(apply.call_args.kwargs["identity"], spec.identity())
|
||||||
|
job.refresh_from_db()
|
||||||
|
zone.refresh_from_db()
|
||||||
|
self.assertTrue(job.active)
|
||||||
|
self.assertEqual(HostingMailbox.objects.count(), 1)
|
||||||
|
self.assertEqual(
|
||||||
|
zone.spec.mx_records,
|
||||||
|
(MxRecord(spec.domain, 10, "mx.example.test"),),
|
||||||
|
)
|
||||||
|
self.assertContains(self.client.get(self.url), "Copy MX record")
|
||||||
|
|
||||||
|
zone.publication.finished_at = timezone.now()
|
||||||
|
zone.publication.save(update_fields=["finished_at"])
|
||||||
|
self.assertRedirects(
|
||||||
|
self.client.post(self.url, {"action": "remove"}), self.url
|
||||||
|
)
|
||||||
|
with patch(
|
||||||
|
"coulobre.hosting.mail_domain_aliases.apply_on_local_node"
|
||||||
|
) as apply:
|
||||||
|
publish_mail_domain_alias.run(job.pk)
|
||||||
|
self.assertTrue(apply.call_args.args[0].remove)
|
||||||
|
self.assertFalse(MailDomainAlias.objects.exists())
|
||||||
|
zone.refresh_from_db()
|
||||||
|
self.assertEqual(zone.spec.mx_records, ())
|
||||||
|
self.assertEqual(HostingMailbox.objects.count(), 1)
|
||||||
|
|
||||||
|
def test_requires_common_owner_and_preserves_existing_mx(self):
|
||||||
|
current = MxRecord(
|
||||||
|
self.source.primary_domain, 10, "external.example.test"
|
||||||
|
)
|
||||||
|
zone = self.zone((current,))
|
||||||
|
self.assertContains(self.queue(), "Review the existing MX targets")
|
||||||
|
self.assertFalse(MailDomainAlias.objects.exists())
|
||||||
|
zone.refresh_from_db()
|
||||||
|
self.assertEqual(zone.spec.mx_records, (current,))
|
||||||
|
|
||||||
|
self.owner.customer = None
|
||||||
|
self.owner.save(update_fields=["customer"])
|
||||||
|
self.assertContains(self.queue(), "Select a valid choice")
|
||||||
|
self.assertFalse(MailDomainAlias.objects.exists())
|
||||||
@@ -52,6 +52,7 @@ from .invitations import AcceptInvitation, ManageInvitation
|
|||||||
from .mail_delivery_views import MailDeliveryView
|
from .mail_delivery_views import MailDeliveryView
|
||||||
from .mail_diagnostics_views import MailDiagnosticsView
|
from .mail_diagnostics_views import MailDiagnosticsView
|
||||||
from .mail_dns_views import MailDnsCheckView, RequestMailDnsSetup
|
from .mail_dns_views import MailDnsCheckView, RequestMailDnsSetup
|
||||||
|
from .mail_domain_alias_views import mail_domain_alias
|
||||||
from .mail_policy_views import (
|
from .mail_policy_views import (
|
||||||
MailRoutingEditor,
|
MailRoutingEditor,
|
||||||
MailSpamEditor,
|
MailSpamEditor,
|
||||||
@@ -265,6 +266,11 @@ urlpatterns = [
|
|||||||
domain_workspace,
|
domain_workspace,
|
||||||
name="domain_workspace",
|
name="domain_workspace",
|
||||||
),
|
),
|
||||||
|
path(
|
||||||
|
"accounts/<int:pk>/mail-domain-alias/<str:domain>/",
|
||||||
|
mail_domain_alias,
|
||||||
|
name="mail_domain_alias",
|
||||||
|
),
|
||||||
path(
|
path(
|
||||||
"hosting/<slug:page>/", customer_workspace, name="customer_workspace"
|
"hosting/<slug:page>/", customer_workspace, name="customer_workspace"
|
||||||
),
|
),
|
||||||
|
|||||||
@@ -105,6 +105,7 @@ from .installation_features import (
|
|||||||
)
|
)
|
||||||
from .invitations import InviteLoginForm, queue_invitation
|
from .invitations import InviteLoginForm, queue_invitation
|
||||||
from .limit_forms import add_unlimited_fields
|
from .limit_forms import add_unlimited_fields
|
||||||
|
from .mail_domain_alias_views import may_manage_aliases
|
||||||
from .mail_policy_views import mail_policy_enabled
|
from .mail_policy_views import mail_policy_enabled
|
||||||
from .mailbox_removal import can_remove_mailbox
|
from .mailbox_removal import can_remove_mailbox
|
||||||
from .models import (
|
from .models import (
|
||||||
@@ -984,6 +985,14 @@ class AccountDetail(TenantScopeMixin, PermissionRequiredMixin, DetailView):
|
|||||||
context["manage_mail_routing"] = mail_policy_enabled(
|
context["manage_mail_routing"] = mail_policy_enabled(
|
||||||
self.request, "routing"
|
self.request, "routing"
|
||||||
)
|
)
|
||||||
|
if may_manage_aliases(self.request):
|
||||||
|
context["mail_alias_domains"] = (
|
||||||
|
self.object.website_domains.order_by("domain")
|
||||||
|
.exclude(
|
||||||
|
domain__in=self.object.mail_domains.values("domain")
|
||||||
|
)
|
||||||
|
.select_related("mail_alias__primary")
|
||||||
|
)
|
||||||
context["manage_mail_vacation"] = mail_policy_enabled(
|
context["manage_mail_vacation"] = mail_policy_enabled(
|
||||||
self.request, "vacation"
|
self.request, "vacation"
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -62,6 +62,10 @@ def queue_alias_operation(account_id, alias_id, operation, *, allow_https):
|
|||||||
if not alias.problem:
|
if not alias.problem:
|
||||||
return
|
return
|
||||||
operation = alias.operation
|
operation = alias.operation
|
||||||
|
if operation == WebsiteAlias.Operation.REMOVE and hasattr(
|
||||||
|
alias.reservation, "mail_alias"
|
||||||
|
):
|
||||||
|
raise ValidationError("Remove the mail domain alias first.")
|
||||||
if operation == WebsiteAlias.Operation.HTTPS:
|
if operation == WebsiteAlias.Operation.HTTPS:
|
||||||
if not allow_https:
|
if not allow_https:
|
||||||
raise PermissionDenied
|
raise PermissionDenied
|
||||||
|
|||||||
@@ -0,0 +1,46 @@
|
|||||||
|
from dataclasses import dataclass
|
||||||
|
|
||||||
|
from .domain_names import canonical_domain
|
||||||
|
from .mail_policy import MailPolicy
|
||||||
|
|
||||||
|
OPERATION = "set_mail_domain_alias"
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True)
|
||||||
|
class MailDomainAliasRequest(MailPolicy):
|
||||||
|
domain: str
|
||||||
|
target: str
|
||||||
|
remove: bool = False
|
||||||
|
|
||||||
|
def __post_init__(self):
|
||||||
|
if not isinstance(self.domain, str) or not isinstance(
|
||||||
|
self.target, str
|
||||||
|
):
|
||||||
|
raise ValueError("Provide the alias and primary mail domains.")
|
||||||
|
for field in ("domain", "target"):
|
||||||
|
object.__setattr__(
|
||||||
|
self, field, canonical_domain(getattr(self, field))
|
||||||
|
)
|
||||||
|
if self.domain == self.target or type(self.remove) is not bool:
|
||||||
|
raise ValueError("Choose a different primary mail domain.")
|
||||||
|
|
||||||
|
def manifest(self):
|
||||||
|
return {
|
||||||
|
"version": 1,
|
||||||
|
"operation": OPERATION,
|
||||||
|
"domain": self.domain,
|
||||||
|
"target": self.target,
|
||||||
|
"remove": self.remove,
|
||||||
|
}
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def from_manifest(cls, data):
|
||||||
|
if (
|
||||||
|
data.keys()
|
||||||
|
!= {"version", "operation", "domain", "target", "remove"}
|
||||||
|
or type(data["version"]) is not int
|
||||||
|
or data["version"] != 1
|
||||||
|
or data["operation"] != OPERATION
|
||||||
|
):
|
||||||
|
raise ValueError("Invalid mail domain alias request.")
|
||||||
|
return cls(data["domain"], data["target"], data["remove"])
|
||||||
@@ -171,6 +171,8 @@ class MailboxRemovalRequest(RetirementRequest):
|
|||||||
|
|
||||||
def parse_mailbox_request(data):
|
def parse_mailbox_request(data):
|
||||||
from .mail_delivery import OPERATION, MailDeliveryRequest
|
from .mail_delivery import OPERATION, MailDeliveryRequest
|
||||||
|
from .mail_domain_alias import OPERATION as DOMAIN_ALIAS_OPERATION
|
||||||
|
from .mail_domain_alias import MailDomainAliasRequest
|
||||||
from .mail_filter_check import OPERATION as FILTER_OPERATION
|
from .mail_filter_check import OPERATION as FILTER_OPERATION
|
||||||
from .mail_filter_check import MailFilterCheckRequest
|
from .mail_filter_check import MailFilterCheckRequest
|
||||||
from .mail_policy import OPERATIONS, parse_mail_policy
|
from .mail_policy import OPERATIONS, parse_mail_policy
|
||||||
@@ -192,6 +194,11 @@ def parse_mailbox_request(data):
|
|||||||
return parse_mailbox_password_request(data)
|
return parse_mailbox_password_request(data)
|
||||||
if isinstance(data, dict) and data.get("operation") == OPERATION:
|
if isinstance(data, dict) and data.get("operation") == OPERATION:
|
||||||
return MailDeliveryRequest.from_manifest(data)
|
return MailDeliveryRequest.from_manifest(data)
|
||||||
|
if (
|
||||||
|
isinstance(data, dict)
|
||||||
|
and data.get("operation") == DOMAIN_ALIAS_OPERATION
|
||||||
|
):
|
||||||
|
return MailDomainAliasRequest.from_manifest(data)
|
||||||
if isinstance(data, dict) and data.get("operation") == FILTER_OPERATION:
|
if isinstance(data, dict) and data.get("operation") == FILTER_OPERATION:
|
||||||
return MailFilterCheckRequest.from_manifest(data)
|
return MailFilterCheckRequest.from_manifest(data)
|
||||||
if isinstance(data, dict) and data.get("operation") in {
|
if isinstance(data, dict) and data.get("operation") in {
|
||||||
@@ -251,6 +258,7 @@ def mailbox_request_identity(spec):
|
|||||||
|
|
||||||
def apply_mailbox_request(request):
|
def apply_mailbox_request(request):
|
||||||
from .mail_delivery import MailDeliveryRequest, inspect_delivery
|
from .mail_delivery import MailDeliveryRequest, inspect_delivery
|
||||||
|
from .mail_domain_alias import MailDomainAliasRequest
|
||||||
from .mail_filter_check import MailFilterCheckRequest, check_spam_filter
|
from .mail_filter_check import MailFilterCheckRequest, check_spam_filter
|
||||||
from .mail_policy import MailRouting, MailVacation
|
from .mail_policy import MailRouting, MailVacation
|
||||||
from .mail_queue import (
|
from .mail_queue import (
|
||||||
@@ -287,6 +295,11 @@ def apply_mailbox_request(request):
|
|||||||
|
|
||||||
apply_routing(request)
|
apply_routing(request)
|
||||||
return None
|
return None
|
||||||
|
if isinstance(request, MailDomainAliasRequest):
|
||||||
|
from .mail_node_routing import apply_domain_alias
|
||||||
|
|
||||||
|
apply_domain_alias(request)
|
||||||
|
return None
|
||||||
if isinstance(request, MailVacation):
|
if isinstance(request, MailVacation):
|
||||||
from .mail_node_vacation import apply_vacation
|
from .mail_node_vacation import apply_vacation
|
||||||
|
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ import json
|
|||||||
import os
|
import os
|
||||||
|
|
||||||
from . import mail_node_apply as mail
|
from . import mail_node_apply as mail
|
||||||
|
from .mail_domain_alias import MailDomainAliasRequest
|
||||||
from .mail_policy import MailRouting, parse_mail_policy
|
from .mail_policy import MailRouting, parse_mail_policy
|
||||||
from .node_files import (
|
from .node_files import (
|
||||||
read_root_file,
|
read_root_file,
|
||||||
@@ -41,6 +42,115 @@ def save_policy(spec):
|
|||||||
path.unlink(missing_ok=True)
|
path.unlink(missing_ok=True)
|
||||||
|
|
||||||
|
|
||||||
|
def domain_alias_path():
|
||||||
|
return mail.STATE_DIRECTORY / "domain-aliases"
|
||||||
|
|
||||||
|
|
||||||
|
def domain_aliases():
|
||||||
|
path = domain_alias_path()
|
||||||
|
if not os.path.lexists(path):
|
||||||
|
return {}
|
||||||
|
data = json.loads(read_root_file(path, mode=0o600))
|
||||||
|
if not isinstance(data, dict):
|
||||||
|
raise ValueError("Invalid mail domain alias registry.")
|
||||||
|
for domain, target in data.items():
|
||||||
|
spec = MailDomainAliasRequest(domain, target)
|
||||||
|
if spec.domain != domain or spec.target != target or target in data:
|
||||||
|
raise ValueError("Invalid mail domain alias registry.")
|
||||||
|
return data
|
||||||
|
|
||||||
|
|
||||||
|
def check_alias_domain_configuration(domain):
|
||||||
|
expected = f"proxy:texthash:{POSTFIX_ALIASES}"
|
||||||
|
for setting in ("virtual_alias_domains", "virtual_alias_maps"):
|
||||||
|
if mail.run("postconf", "-hx", setting) != expected:
|
||||||
|
raise ValueError(
|
||||||
|
f"Configure Postfix {setting} to use the Coulobre alias map."
|
||||||
|
)
|
||||||
|
for setting in ("mydestination", "relay_domains"):
|
||||||
|
destinations = (
|
||||||
|
mail.run("postconf", "-hx", setting).replace(",", " ").split()
|
||||||
|
)
|
||||||
|
if any(
|
||||||
|
unsafe_destination(domain, destination)
|
||||||
|
for destination in destinations
|
||||||
|
):
|
||||||
|
raise ValueError(
|
||||||
|
f"Review Postfix {setting} before assigning this domain."
|
||||||
|
)
|
||||||
|
mail.run("postfix", "check")
|
||||||
|
|
||||||
|
|
||||||
|
def unsafe_destination(domain, destination):
|
||||||
|
value = destination.lower().removeprefix(".").removesuffix(".")
|
||||||
|
# Do not assume that custom tables or patterns exclude the alias.
|
||||||
|
return (
|
||||||
|
not value
|
||||||
|
or any(
|
||||||
|
char not in "abcdefghijklmnopqrstuvwxyz0123456789.-"
|
||||||
|
for char in value
|
||||||
|
)
|
||||||
|
or domain == value
|
||||||
|
or domain.endswith(f".{value}")
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def apply_domain_alias(spec):
|
||||||
|
with mail.locked_state(create=False, exclusive=True) as state:
|
||||||
|
if state is None:
|
||||||
|
raise ValueError("Provision a primary mail domain first.")
|
||||||
|
aliases = domain_aliases()
|
||||||
|
current = aliases.get(spec.domain)
|
||||||
|
if current is not None and current != spec.target:
|
||||||
|
raise ValueError("This alias has a different primary domain.")
|
||||||
|
if spec.remove and current is None:
|
||||||
|
return
|
||||||
|
records = [
|
||||||
|
mail.load_credentials(path)
|
||||||
|
for path in mail.STATE_DIRECTORY.glob("*.json")
|
||||||
|
]
|
||||||
|
recipients = managed_recipients(records)
|
||||||
|
routes = policies()
|
||||||
|
if spec.remove:
|
||||||
|
del aliases[spec.domain]
|
||||||
|
else:
|
||||||
|
check_alias_domain_configuration(spec.domain)
|
||||||
|
if (
|
||||||
|
spec.domain in routes
|
||||||
|
or any(
|
||||||
|
record.mailbox.domain == spec.domain for record in records
|
||||||
|
)
|
||||||
|
or spec.domain in aliases.values()
|
||||||
|
or any(
|
||||||
|
address.endswith(f"@{spec.domain}")
|
||||||
|
for route in routes.values()
|
||||||
|
for address in route.destinations
|
||||||
|
)
|
||||||
|
):
|
||||||
|
raise ValueError(
|
||||||
|
"This alias domain already has independent mail routing."
|
||||||
|
)
|
||||||
|
if spec.target in aliases or not any(
|
||||||
|
address.endswith(f"@{spec.target}") for address in recipients
|
||||||
|
):
|
||||||
|
raise ValueError(
|
||||||
|
"Choose a primary mail domain with a managed mailbox."
|
||||||
|
)
|
||||||
|
aliases[spec.domain] = spec.target
|
||||||
|
|
||||||
|
previous = read_table()
|
||||||
|
try:
|
||||||
|
publish_routes(routes, recipients, previous, aliases=aliases)
|
||||||
|
mail.run("postfix", "reload")
|
||||||
|
replace_configuration(
|
||||||
|
domain_alias_path(), json.dumps(aliases), mode=0o600
|
||||||
|
)
|
||||||
|
except (OSError, ValueError):
|
||||||
|
replace_configuration(POSTFIX_ALIASES, previous)
|
||||||
|
mail.run("postfix", "reload")
|
||||||
|
raise
|
||||||
|
|
||||||
|
|
||||||
def managed_recipients(records):
|
def managed_recipients(records):
|
||||||
return {
|
return {
|
||||||
record.mailbox.address
|
record.mailbox.address
|
||||||
@@ -60,6 +170,7 @@ def apply_routing(spec):
|
|||||||
]
|
]
|
||||||
recipients = managed_recipients(records)
|
recipients = managed_recipients(records)
|
||||||
domains = {address.split("@")[1] for address in recipients}
|
domains = {address.split("@")[1] for address in recipients}
|
||||||
|
aliases = domain_aliases()
|
||||||
if spec.domain not in domains:
|
if spec.domain not in domains:
|
||||||
raise ValueError("Install a managed mailbox on this domain first.")
|
raise ValueError("Install a managed mailbox on this domain first.")
|
||||||
for local in spec.aliases:
|
for local in spec.aliases:
|
||||||
@@ -69,8 +180,9 @@ def apply_routing(spec):
|
|||||||
)
|
)
|
||||||
for address in sorted(spec.destinations):
|
for address in sorted(spec.destinations):
|
||||||
domain = address.split("@")[1]
|
domain = address.split("@")[1]
|
||||||
if domain in domains and (
|
if domain in aliases or (
|
||||||
domain != spec.domain or address not in recipients
|
domain in domains
|
||||||
|
and (domain != spec.domain or address not in recipients)
|
||||||
):
|
):
|
||||||
raise ValueError(
|
raise ValueError(
|
||||||
f"{address} must be a mailbox on this mail domain "
|
f"{address} must be a mailbox on this mail domain "
|
||||||
@@ -81,7 +193,7 @@ def apply_routing(spec):
|
|||||||
routes[spec.domain] = spec
|
routes[spec.domain] = spec
|
||||||
previous = read_table()
|
previous = read_table()
|
||||||
try:
|
try:
|
||||||
publish_routes(routes, recipients, previous)
|
publish_routes(routes, recipients, previous, aliases=aliases)
|
||||||
mail.run("postfix", "reload")
|
mail.run("postfix", "reload")
|
||||||
save_policy(spec)
|
save_policy(spec)
|
||||||
except (OSError, ValueError):
|
except (OSError, ValueError):
|
||||||
@@ -106,13 +218,14 @@ def read_table():
|
|||||||
return contents
|
return contents
|
||||||
|
|
||||||
|
|
||||||
def publish_routes(routes, recipients, previous):
|
def publish_routes(routes, recipients, previous, *, aliases):
|
||||||
domains = {}
|
domains = {}
|
||||||
for address in recipients:
|
for address in recipients:
|
||||||
domain = address.split("@")[1]
|
domain = address.split("@")[1]
|
||||||
domains.setdefault(domain, set()).add(address)
|
domains.setdefault(domain, set()).add(address)
|
||||||
|
|
||||||
rows = set()
|
rows = set()
|
||||||
|
forwarding = {}
|
||||||
for domain, spec in routes.items():
|
for domain, spec in routes.items():
|
||||||
mailboxes = domains.get(domain)
|
mailboxes = domains.get(domain)
|
||||||
if not mailboxes:
|
if not mailboxes:
|
||||||
@@ -129,10 +242,25 @@ def publish_routes(routes, recipients, previous):
|
|||||||
]
|
]
|
||||||
if source not in mailboxes and targets:
|
if source not in mailboxes and targets:
|
||||||
rows.add(f"{source} {','.join(targets)}")
|
rows.add(f"{source} {','.join(targets)}")
|
||||||
|
forwarding.setdefault(domain, set()).add(source)
|
||||||
|
for alias, domain in aliases.items():
|
||||||
|
# Declare the domain and mirror its deliverable recipients.
|
||||||
|
# A wildcard is present only when the primary has a catch-all.
|
||||||
|
rows.add(f"{alias} OK")
|
||||||
|
mailboxes = domains.get(domain, set())
|
||||||
|
for address in mailboxes | forwarding.get(domain, set()):
|
||||||
|
local = address.partition("@")[0]
|
||||||
|
rows.add(f"{local}@{alias} {address}")
|
||||||
|
if (spec := routes.get(domain)) and spec.catchall in mailboxes:
|
||||||
|
rows.add(f"@{alias} {spec.catchall}")
|
||||||
mail.publish_table(POSTFIX_ALIASES, (0o644, None, rows), previous)
|
mail.publish_table(POSTFIX_ALIASES, (0o644, None, rows), previous)
|
||||||
|
|
||||||
|
|
||||||
def check_mailbox_alias(mailbox):
|
def check_mailbox_alias(mailbox):
|
||||||
|
if mailbox.domain in domain_aliases():
|
||||||
|
raise ValueError(
|
||||||
|
"Remove the mail domain alias before adding mailboxes."
|
||||||
|
)
|
||||||
spec = policies().get(mailbox.domain)
|
spec = policies().get(mailbox.domain)
|
||||||
if spec is not None and mailbox.local_part in spec.aliases:
|
if spec is not None and mailbox.local_part in spec.aliases:
|
||||||
raise ValueError(
|
raise ValueError(
|
||||||
@@ -142,7 +270,8 @@ def check_mailbox_alias(mailbox):
|
|||||||
|
|
||||||
def reconcile_routes(records, *, retired=None):
|
def reconcile_routes(records, *, retired=None):
|
||||||
routes = policies()
|
routes = policies()
|
||||||
if not routes:
|
aliases = domain_aliases()
|
||||||
|
if not routes and not aliases:
|
||||||
return
|
return
|
||||||
previous = read_table()
|
previous = read_table()
|
||||||
recipients = managed_recipients(records)
|
recipients = managed_recipients(records)
|
||||||
@@ -168,6 +297,6 @@ def reconcile_routes(records, *, retired=None):
|
|||||||
else:
|
else:
|
||||||
spec = MailRouting(spec.domain, {})
|
spec = MailRouting(spec.domain, {})
|
||||||
routes[spec.domain] = pruned = spec
|
routes[spec.domain] = pruned = spec
|
||||||
publish_routes(routes, recipients, previous)
|
publish_routes(routes, recipients, previous, aliases=aliases)
|
||||||
if pruned is not None:
|
if pruned is not None:
|
||||||
save_policy(pruned)
|
save_policy(pruned)
|
||||||
@@ -103,6 +103,17 @@ def authorized_request(role, spec=None):
|
|||||||
raise ValueError(
|
raise ValueError(
|
||||||
"The panel key is not assigned to this domain."
|
"The panel key is not assigned to this domain."
|
||||||
)
|
)
|
||||||
|
if role == "mail" and spec is not None:
|
||||||
|
from .mail_domain_alias import MailDomainAliasRequest
|
||||||
|
|
||||||
|
if (
|
||||||
|
isinstance(spec, MailDomainAliasRequest)
|
||||||
|
and spec.target not in domains
|
||||||
|
):
|
||||||
|
raise ValueError(
|
||||||
|
"The panel key is not assigned to the primary "
|
||||||
|
"mail domain."
|
||||||
|
)
|
||||||
else:
|
else:
|
||||||
raise ValueError("The peer is not authorized for this receiver.")
|
raise ValueError("The peer is not authorized for this receiver.")
|
||||||
yield
|
yield
|
||||||
|
|||||||
@@ -12,6 +12,7 @@ from uuid import uuid4
|
|||||||
|
|
||||||
from . import node_maintenance, node_setup, receiver_scope
|
from . import node_maintenance, node_setup, receiver_scope
|
||||||
from .dns_node import DnsZone
|
from .dns_node import DnsZone
|
||||||
|
from .mail_domain_alias import MailDomainAliasRequest
|
||||||
from .mail_filter_check import MailFilterCheckRequest
|
from .mail_filter_check import MailFilterCheckRequest
|
||||||
from .mail_node import MailboxQuotaUpdate, MailboxSpec, parse_mailbox_request
|
from .mail_node import MailboxQuotaUpdate, MailboxSpec, parse_mailbox_request
|
||||||
from .mail_policy import MailRouting
|
from .mail_policy import MailRouting
|
||||||
@@ -96,6 +97,26 @@ class ReceiverScopeTests(TestCase):
|
|||||||
with self.assertRaisesRegex(ValueError, "not assigned"):
|
with self.assertRaisesRegex(ValueError, "not assigned"):
|
||||||
check_request("mail", MailQueueRequest("alpha.example.test"))
|
check_request("mail", MailQueueRequest("alpha.example.test"))
|
||||||
|
|
||||||
|
def test_domain_alias_requires_both_domains_in_the_same_scope(self):
|
||||||
|
spec = MailDomainAliasRequest(
|
||||||
|
"alias.example.test", "main.example.test"
|
||||||
|
)
|
||||||
|
spec = parse_mailbox_request(spec.manifest())
|
||||||
|
with (
|
||||||
|
patch.object(
|
||||||
|
receiver_scope,
|
||||||
|
"socket_peer",
|
||||||
|
return_value="coulobre-mail-p-alpha",
|
||||||
|
),
|
||||||
|
patch.object(receiver_scope, "scoped_domains") as scope,
|
||||||
|
):
|
||||||
|
for domains in ({spec.domain}, {spec.target}, set()):
|
||||||
|
scope.return_value = domains
|
||||||
|
with self.assertRaisesRegex(ValueError, "not assigned"):
|
||||||
|
check_request("mail", spec)
|
||||||
|
scope.return_value = {spec.domain, spec.target}
|
||||||
|
check_request("mail", spec)
|
||||||
|
|
||||||
def test_password_requests_never_expose_read_or_cross_panel_access(self):
|
def test_password_requests_never_expose_read_or_cross_panel_access(self):
|
||||||
mailbox = MailboxSpec("alpha.example.test", "sales")
|
mailbox = MailboxSpec("alpha.example.test", "sales")
|
||||||
with self.assertRaisesRegex(ValueError, "password change"):
|
with self.assertRaisesRegex(ValueError, "password change"):
|
||||||
|
|||||||
Reference in new issue
Block a user