From 5ec3d1fa775b00f47f44320ce50dbf45dc10b2a4 Mon Sep 17 00:00:00 2001 From: Peter van Arkel Date: Tue, 1 Dec 2026 14:17:19 +0100 Subject: [PATCH] Archive individual mailboxes on local and linked mail nodes Refs #218. --- docs/deployment.md | 15 ++ src/coulobre/hosting/account_retirement.py | 4 + src/coulobre/hosting/credential_views.py | 2 +- src/coulobre/hosting/domain_services.py | 6 +- src/coulobre/hosting/mail_policies.py | 14 +- src/coulobre/hosting/mailbox_removal.py | 166 ++++++++++++++++++ .../hosting/migrations/0083_mailboxremoval.py | 78 ++++++++ src/coulobre/hosting/models.py | 21 +++ src/coulobre/hosting/resource_requests.py | 6 + src/coulobre/hosting/roundcube.py | 1 + src/coulobre/hosting/service_changes.py | 4 + src/coulobre/hosting/tasks.py | 16 ++ .../templates/hosting/account_detail.html | 17 ++ .../templates/hosting/domain_workspace.html | 6 +- .../hosting/mailbox_management_links.html | 23 ++- .../templates/hosting/mailbox_removal.html | 26 +++ src/coulobre/hosting/test_mail_node_apply.py | 16 +- .../hosting/test_mailbox_provisioning.py | 56 +++++- src/coulobre/hosting/urls.py | 6 + src/coulobre/hosting/views.py | 12 +- src/coulobre/hosting/workspaces.py | 1 + src/coulobre/mail_node.py | 18 +- src/coulobre/mail_node_retirement.py | 8 +- src/coulobre/node_retirement.py | 21 ++- 24 files changed, 512 insertions(+), 31 deletions(-) create mode 100644 src/coulobre/hosting/mailbox_removal.py create mode 100644 src/coulobre/hosting/migrations/0083_mailboxremoval.py create mode 100644 src/coulobre/hosting/templates/hosting/mailbox_removal.html diff --git a/docs/deployment.md b/docs/deployment.md index b215f74..baa5245 100644 --- a/docs/deployment.md +++ b/docs/deployment.md @@ -3094,6 +3094,21 @@ Keep the managed data directories on their service filesystems to allow an atomic move into the archive directory. Existing backup archives remain available to operators with backup access. +### Remove a mailbox + +On **Email Accounts**, choose **Remove mailbox** and confirm the full +address. Remove any forwarders or catch-all destination that use the +address first. If the job fails, retry it from the mailbox list. Removal +stops delivery and login for the selected address and releases its mailbox +slot after the mail node confirms the operation. + +Operators can find the reference under **Hosting accounts โ†’ Email โ†’ +Archived mailboxes**. Retrieve the Maildir by that reference on the mail node +using the table above. To recover messages, provision the destination +mailbox first and import a private copy of the archived Maildir with +Dovecot. The archive is root-only and may contain private credentials. +Recover the messages from the Maildir and set a new password separately. + ## Configure installed features in the panel Open **About Coulobre โ†’ Configure features** as a superuser with a verified diff --git a/src/coulobre/hosting/account_retirement.py b/src/coulobre/hosting/account_retirement.py index 9e18e0f..c70f6de 100644 --- a/src/coulobre/hosting/account_retirement.py +++ b/src/coulobre/hosting/account_retirement.py @@ -236,6 +236,10 @@ def request_retirement(account_id, policy, confirmation, digest, actor): raise ValidationError( "Remove folder SFTP logins before retiring the hosting account." ) + if account.mailbox_removals.filter(mailbox__isnull=False).exists(): + raise ValidationError( + "Finish the mailbox removal before retiring the account." + ) targets = cleanup_targets(account) if policy == Policy.RELEASE: for kind, target, _ in targets: diff --git a/src/coulobre/hosting/credential_views.py b/src/coulobre/hosting/credential_views.py index 4695190..edd086c 100644 --- a/src/coulobre/hosting/credential_views.py +++ b/src/coulobre/hosting/credential_views.py @@ -290,7 +290,7 @@ class DatabaseCredentialView(ServiceCredentialView): class MailboxCredentialView(ServiceCredentialView): kind = CredentialKind.MAILBOX queryset = HostingMailbox.objects.filter( - mail_domain__account__retired_at__isnull=True + mail_domain__account__retired_at__isnull=True, removal__isnull=True ).select_related("mail_domain__account") customer_relation = "mail_domain__account__customer" diff --git a/src/coulobre/hosting/domain_services.py b/src/coulobre/hosting/domain_services.py index e5383ab..bef4ec9 100644 --- a/src/coulobre/hosting/domain_services.py +++ b/src/coulobre/hosting/domain_services.py @@ -208,6 +208,7 @@ def domain_workspace(request, pk, page): "replies": "Automatic replies", } from .mail_policies import mail_policy_available + from .mailbox_removal import can_remove_mailbox from .roundcube import roundcube_available defaults = zone_defaults() if page == "dns" else None @@ -241,6 +242,7 @@ def domain_workspace(request, pk, page): ), "can_edit_routing": mail_policy_available("routing"), "can_edit_mailbox": mail_policy_available("vacation"), + "can_remove_mailbox": can_remove_mailbox(request), "show_mailbox_credentials": show_mailbox_credentials, "show_mailbox_rotation": show_rotation_action( request, CredentialKind.MAILBOX @@ -255,7 +257,9 @@ def domain_workspace(request, pk, page): ), "mail_imap_host": settings.MAIL_IMAP_HOST, "mail_submission_host": settings.MAIL_SUBMISSION_HOST, - "mailboxes": mail_domain.mailboxes.select_related("provisioning") + "mailboxes": mail_domain.mailboxes.select_related( + "provisioning", "removal" + ) if mail_domain else (), "website": website, diff --git a/src/coulobre/hosting/mail_policies.py b/src/coulobre/hosting/mail_policies.py index 1721663..d78e453 100644 --- a/src/coulobre/hosting/mail_policies.py +++ b/src/coulobre/hosting/mail_policies.py @@ -36,6 +36,7 @@ def validate_policy(resource, spec, account): else: mailbox_ready = resource.__class__.objects.filter( pk=resource.pk, + removal__isnull=True, provisioning__finished_at__isnull=False, provisioning__problem="", ).exists() @@ -51,14 +52,17 @@ def validate_routing(domain, spec, plan): mailboxes = domain.mailboxes.all() if mailboxes.filter(local_part__in=spec.aliases).exists(): raise ValidationError("An alias cannot replace a requested mailbox.") + configured = mailboxes.filter( + provisioning__finished_at__isnull=False, + provisioning__problem="", + ) provisioned = { f"{local}@{domain.domain}" - for local in mailboxes.filter( - provisioning__finished_at__isnull=False, - provisioning__problem="", - ).values_list("local_part", flat=True) + for local in configured.filter(removal__isnull=True).values_list( + "local_part", flat=True + ) } - if not provisioned: + if not provisioned and (spec.destinations or not configured.exists()): raise ValidationError("Provision a mailbox on this mail domain first.") for address in sorted(spec.destinations): if address.endswith(f"@{domain.domain}"): diff --git a/src/coulobre/hosting/mailbox_removal.py b/src/coulobre/hosting/mailbox_removal.py new file mode 100644 index 0000000..07b7051 --- /dev/null +++ b/src/coulobre/hosting/mailbox_removal.py @@ -0,0 +1,166 @@ +from django import forms +from django.conf import settings +from django.contrib import messages +from django.contrib.auth.mixins import PermissionRequiredMixin +from django.core.exceptions import ValidationError +from django.db import transaction +from django.http import Http404 +from django.shortcuts import get_object_or_404, redirect +from django.urls import reverse +from django.utils.decorators import method_decorator +from django.utils.functional import cached_property +from django.views.decorators.cache import never_cache +from django.views.generic import FormView + +from coulobre.mail_node import MailboxRemovalRequest +from coulobre.mail_policy import parse_mail_policy + +from .access import can_manage_hosting, customer_for_user +from .domain_policies import require_managed +from .models import HostingAccount, HostingMailbox, MailboxRemoval +from .node_client import apply_on_local_node +from .resource_requests import lock_hosting_account, require_active_services +from .service_credentials import ( + UNCONFIRMED_ROTATION, + CredentialKind, + rotation_history, +) + +PERMISSIONS = ("hosting.view_hostingmailbox", "hosting.delete_hostingmailbox") + + +def can_remove_mailbox(request): + return ( + settings.LOCAL_MAILBOX_PROVISIONING + and getattr(request, "impersonation", None) is None + and can_manage_hosting(request.user, PERMISSIONS) + ) + + +@transaction.atomic +def request_removal(mailbox, actor, customer_id): + account = lock_hosting_account(mailbox.mail_domain.account_id, customer_id) + require_active_services(account) + current = HostingMailbox.objects.select_related("mail_domain").get( + pk=mailbox.pk, mail_domain__account=account + ) + require_managed(account, current.mail_domain.domain, "mail_managed") + existing = getattr(current, "removal", None) + if existing is not None: + MailboxRemoval.objects.requeue( + MailboxRemoval.objects.filter(pk=existing.pk).exclude(problem=""), + ) + return + if getattr(current, "provisioning", None) is None or ( + current.provisioning.state != "configured" + ): + raise ValidationError("Complete the mailbox setup before removing it.") + rotation = rotation_history( + account.pk, CredentialKind.MAILBOX, str(current) + ).first() + if rotation is not None and rotation.outcome in UNCONFIRMED_ROTATION: + raise ValidationError("Finish the mailbox password change first.") + vacation = getattr(current, "vacation", None) + if vacation is not None and vacation.finished_at is None: + raise ValidationError("Wait for the automatic reply change first.") + routing = getattr(current.mail_domain, "routing", None) + if routing is not None and ( + routing.finished_at is None + or any( + str(current) in parse_mail_policy(manifest).destinations + for manifest in (routing.manifest, routing.applied_manifest) + if manifest + ) + ): + raise ValidationError( + "Remove forwarders and catch-all destinations that use this " + "mailbox, then wait for the routing change to apply." + ) + MailboxRemoval.objects.create( + account=account, mailbox=current, actor=actor, address=str(current) + ) + + +def apply_removal(job): + if job.mailbox is None: + return + request = MailboxRemovalRequest(job.mailbox.spec, str(job.archive_id)) + apply_on_local_node( + request, + "/run/coulobre-mail-apply.sock", + "mail node", + "mailbox removal", + identity=request.identity(), + ) + with transaction.atomic(): + lock_hosting_account(job.account_id, customer_id=None) + HostingMailbox.objects.filter(pk=job.mailbox_id, removal=job).delete() + + +class ConfirmMailboxRemoval(forms.Form): + address = forms.CharField(label="Email address to remove", max_length=254) + + +@method_decorator(never_cache, name="dispatch") +class MailboxRemovalView(PermissionRequiredMixin, FormView): + form_class = ConfirmMailboxRemoval + template_name = "hosting/mailbox_removal.html" + + def has_permission(self): + return can_remove_mailbox(self.request) + + @cached_property + def customer(self): + return customer_for_user(self.request.user) + + @cached_property + def mailbox(self): + mailboxes = HostingMailbox.objects.select_related( + "mail_domain__account", "removal" + ).filter(mail_domain__account__retired_at__isnull=True) + if self.customer is not None: + mailboxes = mailboxes.filter( + mail_domain__account__customer=self.customer + ) + return get_object_or_404(mailboxes, pk=self.kwargs["pk"]) + + def get_success_url(self): + account = self.mailbox.mail_domain.account + if self.customer is not None: + return reverse( + "panel:domain_workspace", + args=[account.pk, "email"], + query={"domain": self.mailbox.mail_domain.domain}, + ) + return account.get_absolute_url() + "#email" + + def get_context_data(self, **kwargs): + return super().get_context_data( + mailbox=self.mailbox, + removal=getattr(self.mailbox, "removal", None), + return_url=self.get_success_url(), + **kwargs, + ) + + def form_valid(self, form): + if form.cleaned_data["address"] != str(self.mailbox): + form.add_error( + "address", "Enter the full email address shown above." + ) + return self.form_invalid(form) + try: + request_removal( + self.mailbox, + self.request.user, + self.customer.pk if self.customer is not None else None, + ) + except ( + HostingAccount.DoesNotExist, + HostingMailbox.DoesNotExist, + ) as error: + raise Http404 from error + except ValidationError as error: + form.add_error(None, error) + return self.form_invalid(form) + messages.success(self.request, "Mailbox removal queued.") + return redirect(self.get_success_url()) diff --git a/src/coulobre/hosting/migrations/0083_mailboxremoval.py b/src/coulobre/hosting/migrations/0083_mailboxremoval.py new file mode 100644 index 0000000..6cd6344 --- /dev/null +++ b/src/coulobre/hosting/migrations/0083_mailboxremoval.py @@ -0,0 +1,78 @@ +# Generated by Django 5.2.19 on 2026-12-01 13:15 + +import uuid + +import django.db.models.deletion +import django.utils.timezone +from django.conf import settings +from django.db import migrations, models + + +class Migration(migrations.Migration): + dependencies = [ + ("hosting", "0082_readable_database_names"), + migrations.swappable_dependency(settings.AUTH_USER_MODEL), + ] + + operations = [ + migrations.CreateModel( + name="MailboxRemoval", + 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)), + ( + "archive_id", + models.UUIDField( + default=uuid.uuid4, editable=False, unique=True + ), + ), + ("address", models.CharField(max_length=254)), + ( + "account", + models.ForeignKey( + on_delete=django.db.models.deletion.CASCADE, + related_name="mailbox_removals", + to="hosting.hostingaccount", + ), + ), + ( + "actor", + models.ForeignKey( + null=True, + on_delete=django.db.models.deletion.SET_NULL, + to=settings.AUTH_USER_MODEL, + ), + ), + ( + "mailbox", + models.OneToOneField( + null=True, + on_delete=django.db.models.deletion.SET_NULL, + related_name="removal", + to="hosting.hostingmailbox", + ), + ), + ], + options={ + "abstract": False, + }, + ), + ] diff --git a/src/coulobre/hosting/models.py b/src/coulobre/hosting/models.py index 07fa097..d976cb2 100644 --- a/src/coulobre/hosting/models.py +++ b/src/coulobre/hosting/models.py @@ -1523,6 +1523,27 @@ class MailboxProvisioning(ProvisioningJob): quota_update = models.BooleanField(default=False) +class MailboxRemoval(ProvisioningJob): + archive_id = models.UUIDField( + default=uuid.uuid4, unique=True, editable=False + ) + mailbox = models.OneToOneField( + HostingMailbox, + on_delete=models.SET_NULL, + null=True, + related_name="removal", + ) + account = models.ForeignKey( + HostingAccount, + on_delete=models.CASCADE, + related_name="mailbox_removals", + ) + actor = models.ForeignKey( + settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True + ) + address = models.CharField(max_length=254) + + class MailPolicyPublication(ProvisioningJob): manifest = models.JSONField() applied_manifest = models.JSONField(default=dict, blank=True) diff --git a/src/coulobre/hosting/resource_requests.py b/src/coulobre/hosting/resource_requests.py index 612eefc..a875491 100644 --- a/src/coulobre/hosting/resource_requests.py +++ b/src/coulobre/hosting/resource_requests.py @@ -157,6 +157,10 @@ def queue_mailbox_provisioning(mailbox): ) require_managed(account, mailbox.mail_domain.domain, "mail_managed") require_active_services(account) + if not HostingMailbox.objects.filter( + pk=mailbox.pk, removal__isnull=True + ).exists(): + raise ValidationError("This mailbox is being removed.") return MailboxProvisioning.objects.queue(mailbox=mailbox) @@ -208,6 +212,8 @@ def change_mailbox_quota(mailbox, quota_mib, *, customer_id=None): current = HostingMailbox.objects.select_related("mail_domain").get( pk=mailbox.pk, mail_domain__account=account ) + if hasattr(current, "removal"): + raise ValidationError("This mailbox is being removed.") if customer_id is not None: require_managed(account, current.mail_domain.domain, "mail_managed") limit = customer_mailbox_quota_limit(account) diff --git a/src/coulobre/hosting/roundcube.py b/src/coulobre/hosting/roundcube.py index 6006ec0..8dc4588 100644 --- a/src/coulobre/hosting/roundcube.py +++ b/src/coulobre/hosting/roundcube.py @@ -43,6 +43,7 @@ def mailbox_can_open_webmail(mailbox): return ( not account.services_suspended and account.retired_at is None + and not hasattr(mailbox, "removal") and (job is None or job.state == "configured") ) diff --git a/src/coulobre/hosting/service_changes.py b/src/coulobre/hosting/service_changes.py index 45ff69a..8e92a1e 100644 --- a/src/coulobre/hosting/service_changes.py +++ b/src/coulobre/hosting/service_changes.py @@ -120,6 +120,10 @@ def current_service_jobs(account): def request_service_change(account_id, action, operator_username): account = lock_hosting_account(account_id, customer_id=None) require_open_account(account) + if account.mailbox_removals.filter(mailbox__isnull=False).exists(): + raise ValidationError( + "Finish the mailbox removal before changing account access." + ) previous = account.service_changes.first() jobs = list(previous.jobs.all()) if previous is not None else [] if any(job.finished_at is None for job in jobs): diff --git a/src/coulobre/hosting/tasks.py b/src/coulobre/hosting/tasks.py index 00453d0..c147384 100644 --- a/src/coulobre/hosting/tasks.py +++ b/src/coulobre/hosting/tasks.py @@ -37,6 +37,7 @@ from .backup_retention import plan_backup_expirations from .independent_websites import active_websites, apply_website_operation from .mail_dns_setup import sync_mail_dns from .mail_policies import apply_policy, mail_policy_available +from .mailbox_removal import apply_removal from .models import ( AccountBackupExpiration, AccountBackupJob, @@ -52,6 +53,7 @@ from .models import ( HostingMailDomain, IndependentWebsite, MailboxProvisioning, + MailboxRemoval, MailDeliverySearch, MailRoutingPublication, MailVacationPublication, @@ -311,6 +313,9 @@ def dispatch_mailbox_provisioning(): dispatch_provisioning_jobs( MailboxProvisioning, provision_mailbox, MAILBOX_PROVISIONING_QUEUE ) + dispatch_provisioning_jobs( + MailboxRemoval, remove_mailbox, MAILBOX_PROVISIONING_QUEUE + ) if mail_policy_available("routing"): dispatch_provisioning_jobs( @@ -801,6 +806,17 @@ def apply_mailbox_provisioning(provisioning): provision_local_mailbox(provisioning.mailbox.spec) +@shared_task(acks_late=True, reject_on_worker_lost=True) +def remove_mailbox(removal_id): + if settings.LOCAL_MAILBOX_PROVISIONING: + run_provisioning_job( + MailboxRemoval.objects.select_related("mailbox__mail_domain"), + removal_id, + apply_removal, + "Could not reach the mail node. Check its connection and retry.", + ) + + @shared_task(acks_late=True, reject_on_worker_lost=True) def publish_mail_routing(job_id): if mail_policy_available("routing"): diff --git a/src/coulobre/hosting/templates/hosting/account_detail.html b/src/coulobre/hosting/templates/hosting/account_detail.html index 31eadae..de97167 100644 --- a/src/coulobre/hosting/templates/hosting/account_detail.html +++ b/src/coulobre/hosting/templates/hosting/account_detail.html @@ -332,6 +332,9 @@ {% if mailbox.quota_mib is not None %}{{ mailbox.quota_mib }} MiB{% else %}Unlimited{% endif %}
+ {% if mailbox.removal %} + Removal {{ mailbox.removal.state }} + {% else %} {% if manage_mailbox_provisioning %} {% url 'panel:mailbox_provision' mailbox.pk as provision_url %} {% include "hosting/resource_provisioning.html" with provisioning=mailbox.provisioning enabled=local_mailbox_enabled action=provision_url resource=mailbox provision_label="Provision mailbox" %} @@ -354,6 +357,7 @@ {% if is_operator %} Download manifest {% endif %} + {% endif %} {% include "hosting/mailbox_management_links.html" %}
{% if is_operator and manage_mailbox_provisioning and mailbox.provisioning.problem %} @@ -369,6 +373,19 @@

No mailboxes yet.

{% endif %} + {% if archived_mailboxes %} +
+

Archived mailboxes

+
+ + + {% for archive in archived_mailboxes %} + + {% endfor %} +
Email addressRemovedMail node archive ID
{{ archive.address }}{{ archive.finished_at }}{{ archive.archive_id }}
+
+
+ {% endif %} {% endif %} {% if show_account_backups or export_backup_manifest %} diff --git a/src/coulobre/hosting/templates/hosting/domain_workspace.html b/src/coulobre/hosting/templates/hosting/domain_workspace.html index 8efe95c..6e47263 100644 --- a/src/coulobre/hosting/templates/hosting/domain_workspace.html +++ b/src/coulobre/hosting/templates/hosting/domain_workspace.html @@ -53,12 +53,14 @@
{% for mailbox in mailboxes %}
Email addressQuotaStateActions
{{ mailbox.spec.address }}{{ mailbox.quota_mib|default_if_none:"Unlimited" }}{% if mailbox.quota_mib %} MiB{% endif %} - {% if mailbox.provisioning.quota_update and mailbox.provisioning.state != 'configured' %} + {% if mailbox.removal %} + Removal {{ mailbox.removal.state }} + {% elif mailbox.provisioning.quota_update and mailbox.provisioning.state != 'configured' %} Storage limit change {{ mailbox.provisioning.state }} {% else %}{{ mailbox.provisioning.state|default:"Requested"|capfirst }}{% endif %}
- {% if mailbox.provisioning.state == 'configured' %} + {% if mailbox.provisioning.state == 'configured' and not mailbox.removal %} {% if show_mailbox_credentials %} Credentials {% elif not show_mailbox_rotation and not customer_mailbox_quota %}Use the current mailbox password{% endif %} diff --git a/src/coulobre/hosting/templates/hosting/mailbox_management_links.html b/src/coulobre/hosting/templates/hosting/mailbox_management_links.html index 58c8500..b7b4c6c 100644 --- a/src/coulobre/hosting/templates/hosting/mailbox_management_links.html +++ b/src/coulobre/hosting/templates/hosting/mailbox_management_links.html @@ -1,8 +1,17 @@ -{% if show_mailbox_rotation and mailbox.provisioning.state == "configured" %} - Change password -{% endif %} -{% if change_mailbox_quota or customer_mailbox_quota and mailbox.provisioning.state == "configured" %} - Change storage limit -{% elif customer_mailbox_quota and mailbox.provisioning.state == "failed" and mailbox.provisioning.quota_update %} - Retry storage limit change +{% if mailbox.removal %} + {% if can_remove_mailbox and mailbox.removal.problem %} + Retry removal + {% endif %} +{% else %} + {% if show_mailbox_rotation and mailbox.provisioning.state == "configured" %} + Change password + {% endif %} + {% if change_mailbox_quota or customer_mailbox_quota and mailbox.provisioning.state == "configured" %} + Change storage limit + {% elif customer_mailbox_quota and mailbox.provisioning.state == "failed" and mailbox.provisioning.quota_update %} + Retry storage limit change + {% endif %} + {% if can_remove_mailbox and mailbox.provisioning.state == "configured" %} + Remove mailbox + {% endif %} {% endif %} diff --git a/src/coulobre/hosting/templates/hosting/mailbox_removal.html b/src/coulobre/hosting/templates/hosting/mailbox_removal.html new file mode 100644 index 0000000..fa6e350 --- /dev/null +++ b/src/coulobre/hosting/templates/hosting/mailbox_removal.html @@ -0,0 +1,26 @@ +{% extends "hosting/base.html" %} + +{% block title %}Remove mailbox ยท Coulobre Panel{% endblock %} +{% block content %} +
+

Remove mailbox

+

{{ mailbox }}

+
+
+ {% if removal.problem %}

{{ removal.problem }}

{% endif %} + {% if removal and not removal.problem %} +

Mailbox removal {{ removal.state }}.

+ Back to mailboxes + {% else %} +

Stop delivery and sign-in for this address. An operator can recover the archived messages on the mail server.

+
+ {% csrf_token %} + {{ form.as_p }} +
+ + Cancel +
+
+ {% endif %} +
+{% endblock %} diff --git a/src/coulobre/hosting/test_mail_node_apply.py b/src/coulobre/hosting/test_mail_node_apply.py index 89df456..f110ba5 100644 --- a/src/coulobre/hosting/test_mail_node_apply.py +++ b/src/coulobre/hosting/test_mail_node_apply.py @@ -12,7 +12,12 @@ from uuid import uuid4 from django.test import SimpleTestCase -from coulobre.mail_node import MailboxQuotaUpdate, MailboxSpec, main +from coulobre.mail_node import ( + MailboxQuotaUpdate, + MailboxRemovalRequest, + MailboxSpec, + main, +) from coulobre.mail_node_apply import ( apply_mailbox, check_dovecot_maildir, @@ -81,6 +86,15 @@ class MailboxApplyRequestTests(SimpleTestCase): change.assert_called_once_with(mailbox) self.apply.assert_not_called() + def test_removal_request_can_archive_an_active_mailbox(self): + removal = MailboxRemovalRequest(self.mailbox, str(uuid4())) + with patch("coulobre.mail_node_retirement.retire_mailbox") as retire: + code, reply = self.request(removal.manifest()) + self.assertEqual(code, 0) + self.assertEqual(reply["operation_id"], removal.operation_id) + retire.assert_called_once_with(removal, allow_active=True) + self.apply.assert_not_called() + class MailboxApplyTests(SimpleTestCase): def setUp(self): diff --git a/src/coulobre/hosting/test_mailbox_provisioning.py b/src/coulobre/hosting/test_mailbox_provisioning.py index d687855..047229c 100644 --- a/src/coulobre/hosting/test_mailbox_provisioning.py +++ b/src/coulobre/hosting/test_mailbox_provisioning.py @@ -15,9 +15,14 @@ from .models import ( HostingMailDomain, HostingPlan, MailboxProvisioning, + MailboxRemoval, Reseller, ) -from .tasks import dispatch_mailbox_provisioning, provision_mailbox +from .tasks import ( + dispatch_mailbox_provisioning, + provision_mailbox, + remove_mailbox, +) @override_settings(LOCAL_MAILBOX_PROVISIONING=True) @@ -124,6 +129,55 @@ class MailboxProvisioningTests(TestCase): self.assertEqual(job.state, "queued") self.assertFalse(job.problem) + def test_customer_mailbox_removal_retries_and_retains_archive_reference( + self, + ): + MailboxProvisioning.objects.create( + mailbox=self.mailbox, finished_at=timezone.now() + ) + self.client.force_login(self.customer) + url = reverse("panel:mailbox_removal", args=[self.mailbox.pk]) + self.assertContains(self.client.get(url), "Remove mailbox") + self.assertContains( + self.client.post(url, {"address": "other@site.example"}), + "Enter the full email address", + ) + self.assertFalse(MailboxRemoval.objects.exists()) + self.assertEqual( + self.client.post(url, {"address": str(self.mailbox)}).status_code, + 302, + ) + job = MailboxRemoval.objects.get() + with patch( + "coulobre.hosting.mailbox_removal.apply_on_local_node", + side_effect=[OSError(), {}], + ) as apply: + remove_mailbox.run(job.pk) + job.refresh_from_db() + self.assertEqual(job.state, "failed") + self.assertContains(self.client.get(url), "Retry removal") + self.client.post(url, {"address": str(self.mailbox)}) + remove_mailbox.run(job.pk) + job.refresh_from_db() + self.assertEqual(job.state, "configured") + self.assertEqual(apply.call_args_list[0], apply.call_args_list[1]) + self.assertIsNone(job.mailbox_id) + self.assertEqual(job.address, "support@site.example") + self.assertFalse( + HostingMailbox.objects.filter(pk=self.mailbox.pk).exists() + ) + + def test_other_customer_cannot_remove_mailbox(self): + user = get_user_model().objects.create_user("other-customer") + Customer.objects.create(user=user) + self.client.force_login(user) + url = reverse("panel:mailbox_removal", args=[self.mailbox.pk]) + self.assertEqual( + self.client.post(url, {"address": str(self.mailbox)}).status_code, + 404, + ) + self.assertFalse(MailboxRemoval.objects.exists()) + def allow_quota_changes(self, user): user.user_permissions.add( Permission.objects.get( diff --git a/src/coulobre/hosting/urls.py b/src/coulobre/hosting/urls.py index fe4bc8c..35b17db 100644 --- a/src/coulobre/hosting/urls.py +++ b/src/coulobre/hosting/urls.py @@ -56,6 +56,7 @@ from .mail_policy_views import ( MailVacationEditor, ) from .mail_queue_views import MailQueueIndex, MailQueueView, mail_queue_action +from .mailbox_removal import MailboxRemovalView from .operator_backups import OperatorBackupsView from .operator_tools import ( ConnectedNodesView, @@ -719,6 +720,11 @@ urlpatterns = [ views.MailboxQuotaEdit.as_view(), name="mailbox_quota", ), + path( + "mailboxes//remove/", + MailboxRemovalView.as_view(), + name="mailbox_removal", + ), path( "mailboxes//provision/", views.RequestMailboxProvisioning.as_view(), diff --git a/src/coulobre/hosting/views.py b/src/coulobre/hosting/views.py index 9f1401d..cbf8e77 100644 --- a/src/coulobre/hosting/views.py +++ b/src/coulobre/hosting/views.py @@ -106,6 +106,7 @@ from .installation_features import ( from .invitations import InviteLoginForm, queue_invitation from .limit_forms import add_unlimited_fields from .mail_policy_views import mail_policy_enabled +from .mailbox_removal import can_remove_mailbox from .models import ( AccountBackupJob, AccountBackupSchedule, @@ -985,7 +986,16 @@ class AccountDetail(TenantScopeMixin, PermissionRequiredMixin, DetailView): ) mailboxes = HostingMailbox.objects.filter( mail_domain__account=self.object - ).select_related("mail_domain", "provisioning") + ).select_related("mail_domain", "provisioning", "removal") + context["can_remove_mailbox"] = can_remove_mailbox(self.request) + if context["can_remove_mailbox"] and not tenant: + context["archived_mailboxes"] = ( + self.object.mailbox_removals.filter( + mailbox__isnull=True, + finished_at__isnull=False, + problem="", + ).order_by("-finished_at")[:20] + ) if not tenant and user.has_perms(PROVISION_MAILBOX): context["manage_mailbox_provisioning"] = True context["local_mailbox_enabled"] = panel_feature_allowed( diff --git a/src/coulobre/hosting/workspaces.py b/src/coulobre/hosting/workspaces.py index f261708..9e49eea 100644 --- a/src/coulobre/hosting/workspaces.py +++ b/src/coulobre/hosting/workspaces.py @@ -68,6 +68,7 @@ CUSTOMER_NAV_ROUTES = { "mailbox_credentials": "email", "mailbox_credential_rotation": "email", "mailbox_quota": "email", + "mailbox_removal": "email", "mail_routing": "forwarders", "mail_vacation": "replies", "mail_spam": "spam", diff --git a/src/coulobre/mail_node.py b/src/coulobre/mail_node.py index fc9235c..9323857 100644 --- a/src/coulobre/mail_node.py +++ b/src/coulobre/mail_node.py @@ -165,6 +165,10 @@ class MailboxSigningRequest: } +class MailboxRemovalRequest(RetirementRequest): + operation = "remove_mailbox" + + def parse_mailbox_request(data): from .mail_delivery import OPERATION, MailDeliveryRequest from .mail_policy import OPERATIONS, parse_mail_policy @@ -188,6 +192,16 @@ def parse_mailbox_request(data): return MailQueueAction.from_manifest(data) if isinstance(data, dict) and data.get("operation") in OPERATIONS: return parse_mail_policy(data) + if ( + isinstance(data, dict) + and data.get("operation") == MailboxRemovalRequest.operation + ): + return parse_retirement( + data, + MailboxSpec.from_manifest, + parse_mailbox_apply, + MailboxRemovalRequest, + ) return parse_retirement( data, MailboxSpec.from_manifest, parse_mailbox_apply ) @@ -253,7 +267,9 @@ def apply_mailbox_request(request): if isinstance(request, RetirementRequest): from .mail_node_retirement import retire_mailbox - retire_mailbox(request) + retire_mailbox( + request, allow_active=isinstance(request, MailboxRemovalRequest) + ) elif isinstance(request, ServiceAccessRequest): from .mail_node_quota import set_mailbox_access diff --git a/src/coulobre/mail_node_retirement.py b/src/coulobre/mail_node_retirement.py index 20c603a..9b45508 100644 --- a/src/coulobre/mail_node_retirement.py +++ b/src/coulobre/mail_node_retirement.py @@ -13,7 +13,7 @@ from .node_retirement import ( ) -def retire_mailbox(request): +def retire_mailbox(request, *, allow_active=False): mailbox = request.resource path = mail.credential_path(mailbox) with mail.locked_state(create=False, exclusive=True) as state: @@ -43,12 +43,12 @@ def retire_mailbox(request): if os.path.lexists(path): record = mail.load_credentials(path) mail.check_registered_manifest(record, mailbox) - if not record.suspended or ( - not started and not mail.home_is_prepared(record) - ): + if not record.suspended and not allow_active: raise ValueError( "Suspend the managed mailbox before retiring it." ) + if not started and not mail.home_is_prepared(record): + raise ValueError("Complete mailbox setup before retiring it.") elif ( not started or not (retirement.directory / "credentials").is_file() ): diff --git a/src/coulobre/node_retirement.py b/src/coulobre/node_retirement.py index 78a6b34..ada1243 100644 --- a/src/coulobre/node_retirement.py +++ b/src/coulobre/node_retirement.py @@ -12,6 +12,7 @@ OPERATION = "retire_resource" class RetirementRequest: resource: object operation_id: str + operation = OPERATION def __post_init__(self): try: @@ -22,24 +23,30 @@ class RetirementRequest: raise ValueError("Expected a valid retirement operation ID.") def identity(self): - return {"operation": OPERATION, "operation_id": self.operation_id} + return { + "operation": self.operation, + "operation_id": self.operation_id, + } def manifest(self): return { - "operation": OPERATION, + "operation": self.operation, "resource": self.resource.manifest(), "operation_id": self.operation_id, } -def parse_retirement(data, parse_resource, fallback): - if not isinstance(data, dict) or data.get("operation") != OPERATION: +def parse_retirement( + data, parse_resource, fallback, request_type=RetirementRequest +): + if ( + not isinstance(data, dict) + or data.get("operation") != request_type.operation + ): return fallback(data) if data.keys() != {"operation", "resource", "operation_id"}: raise ValueError("Expected a retirement request.") - return RetirementRequest( - parse_resource(data["resource"]), data["operation_id"] - ) + return request_type(parse_resource(data["resource"]), data["operation_id"]) class RetirementRecord: