Files
coulobre/src/coulobre/hosting/mail_policies.py
T

115 lines
4.1 KiB
Python

from django.conf import settings
from django.core.exceptions import PermissionDenied, ValidationError
from django.db import transaction
from coulobre.mail_policy import MailRouting, parse_mail_policy
from .access import is_tenant, manages_account
from .models import HostingMailDomain
from .node_client import apply_on_local_node
from .resource_requests import lock_hosting_account, require_active_services
def mail_policy_available(kind):
return settings.LOCAL_MAILBOX_PROVISIONING and (
settings.MAIL_ROUTING if kind == "routing" else settings.MAIL_VACATION
)
def policy_account(resource):
if isinstance(resource, HostingMailDomain):
return resource.account
return resource.mail_domain.account
def validate_policy(resource, spec, account):
require_active_services(account)
if isinstance(spec, MailRouting):
validate_routing(resource, spec, account.hosting_plan)
else:
mailbox_ready = resource.__class__.objects.filter(
pk=resource.pk,
provisioning__finished_at__isnull=False,
provisioning__problem="",
).exists()
if not mailbox_ready:
raise ValidationError(
"Provision this mailbox before setting replies."
)
def validate_routing(domain, spec, plan):
if spec.catchall and not (plan and plan.allow_mail_catchall):
raise ValidationError("This hosting plan does not allow catch-all.")
mailboxes = domain.mailboxes.all()
if mailboxes.filter(local_part__in=spec.aliases).exists():
raise ValidationError("An alias cannot replace a requested mailbox.")
provisioned = {
f"{local}@{domain.domain}"
for local in mailboxes.filter(
provisioning__finished_at__isnull=False,
provisioning__problem="",
).values_list("local_part", flat=True)
}
if not provisioned:
raise ValidationError("Provision a mailbox on this mail domain first.")
for address in sorted(spec.destinations):
if address.endswith(f"@{domain.domain}"):
if address not in provisioned:
raise ValidationError(
f"Provision the mailbox {address} first."
)
elif not (plan and plan.allow_external_mail_forwarding):
raise ValidationError(
"This hosting plan does not allow external forwarding."
)
@transaction.atomic
def queue_policy(jobs, target, resource, spec, expected_revision, actor):
account = lock_hosting_account(
policy_account(resource).pk, customer_id=None
)
if is_tenant(actor) and not manages_account(actor, account):
raise PermissionDenied
validate_policy(resource, spec, account)
existing = jobs.select_for_update().filter(**{target: resource}).first()
if policy_revision(existing) != expected_revision:
raise ValidationError("These settings changed. Reload and try again.")
manifest = spec.manifest()
if existing is None:
jobs.create(**{target: resource}, manifest=manifest)
elif existing.finished_at is None:
if existing.manifest != manifest:
raise ValidationError("Wait for the pending change to finish.")
else:
jobs.requeue(jobs.filter(pk=existing.pk), manifest=manifest)
def policy_revision(job):
return job.requested_at.isoformat() if job else ""
def apply_policy(job, resource):
spec = parse_mail_policy(job.manifest)
expected = (
resource.domain if isinstance(spec, MailRouting) else str(resource)
)
identity = (
spec.domain if isinstance(spec, MailRouting) else spec.mailbox.address
)
if expected != identity:
raise ValueError("The policy belongs to a different mail resource.")
try:
validate_policy(resource, spec, policy_account(resource))
except ValidationError as error:
raise ValueError(" ".join(error.messages)) from None
apply_on_local_node(
spec,
"/run/coulobre-mail-apply.sock",
"mail node",
"mail policy",
identity=spec.identity(),
)
return {"applied_manifest": job.manifest}