diff --git a/docs/deployment.md b/docs/deployment.md index 7b694d6..4ef32aa 100644 --- a/docs/deployment.md +++ b/docs/deployment.md @@ -482,6 +482,11 @@ Set a per-mailbox storage limit on the hosting plan for new mailbox requests. Enable Dovecot quota enforcement on the mail node before provisioning them. [Mailbox storage limits](development.md#enforce-mailbox-storage-limits) +For an existing mailbox, change its limit from the account page. Coulobre +queues the update for mailboxes provisioned through the local worker. Use +the node command for manually provisioned mailboxes. +[Change a mailbox storage limit](development.md#change-a-mailbox-storage-limit) + Back up mail on the node that hosts the mailbox. The archive can be used to recover messages and folders into a newly provisioned mailbox with the same address. [Mailbox backup and restore](development.md#back-up-and-restore-a-mailbox) diff --git a/docs/development.md b/docs/development.md index ca8361c..fe5a49e 100644 --- a/docs/development.md +++ b/docs/development.md @@ -37,7 +37,9 @@ assigned limit. Leave the field blank to omit a Coulobre storage limit. Changing or reassigning a plan preserves existing databases and mailboxes. If the new limit is at or below current usage, the panel blocks additional -requests of that type. Storage limit changes apply to new mailbox requests. +requests of that type. Changing the plan's storage limit applies to new +mailbox requests. Use **Change storage limit** for an individual mailbox. +[Change a mailbox storage limit](#change-a-mailbox-storage-limit) ## Give a reseller access to assigned accounts @@ -502,6 +504,28 @@ address using a password hash. Postfix accepts listed recipients and hands delivery to Dovecot over the local LMTP socket. Reapply the same manifest to resume installation with the same credentials. +### Change a mailbox storage limit + +On the account page, select **Change storage limit** next to the mailbox. +Enter the new limit in MiB or leave the field blank for unlimited storage. +This action requires mailbox provisioning and change permissions. For a +mailbox already provisioned through the panel, saving queues an update on +the local mail node. Use **Retry provisioning** to retry a failed update +before setting another limit. + +For a mailbox provisioned manually, download its updated manifest and run +the following command on the mail node. + +```sh +sudo /opt/coulobre/bin/coulobre-mail-node set-quota coulobre-mailbox-1.json +``` + +The command changes the quota for the existing mailbox with that address. +Its messages and credentials remain available. If a lower limit is below +current usage, Dovecot enforces the limit on new mail. Reconnect IMAP clients +to pick up the new setting. If the command is interrupted, retry it with +the same manifest. + ### Check a mailbox installation Run the status command on the mail node with the same manifest. @@ -578,6 +602,9 @@ provisioning. Send one version 1 or 2 mailbox manifest as UTF-8 JSON to half of the connection and read the JSON reply to EOF. For a valid manifest, the reply identifies the mailbox and reports `configured` or `failed`. The generated password stays in a root-only credentials file on the mail node. +For an existing mailbox, the same socket accepts a request with +`"operation": "set_quota"` and the updated manifest under `"mailbox"`. +The reply includes both fields. ## Inspect a DirectAdmin backup diff --git a/src/coulobre/hosting/migrations/0022_mailbox_quota_updates.py b/src/coulobre/hosting/migrations/0022_mailbox_quota_updates.py new file mode 100644 index 0000000..b634aa9 --- /dev/null +++ b/src/coulobre/hosting/migrations/0022_mailbox_quota_updates.py @@ -0,0 +1,17 @@ +# Generated by Django 5.2.19 on 2026-11-21 12:27 + +from django.db import migrations, models + + +class Migration(migrations.Migration): + dependencies = [ + ("hosting", "0021_mailbox_storage_limits"), + ] + + operations = [ + migrations.AddField( + model_name="mailboxprovisioning", + name="quota_update", + field=models.BooleanField(default=False), + ), + ] diff --git a/src/coulobre/hosting/models.py b/src/coulobre/hosting/models.py index 18d5041..36a7dd6 100644 --- a/src/coulobre/hosting/models.py +++ b/src/coulobre/hosting/models.py @@ -441,3 +441,4 @@ class MailboxProvisioning(ProvisioningJob): mailbox = models.OneToOneField( HostingMailbox, on_delete=models.CASCADE, related_name="provisioning" ) + quota_update = models.BooleanField(default=False) diff --git a/src/coulobre/hosting/node_client.py b/src/coulobre/hosting/node_client.py index 07a08f3..5b3e933 100644 --- a/src/coulobre/hosting/node_client.py +++ b/src/coulobre/hosting/node_client.py @@ -5,6 +5,7 @@ from coulobre.account_backup_request import ( BACKUP_SOCKET, BACKUP_TIMEOUT_SECONDS, ) +from coulobre.mail_node import MailboxQuotaUpdate RESPONSE_LIMIT = 32768 @@ -56,6 +57,15 @@ def provision_local_mailbox(mailbox): ) +def update_local_mailbox_quota(mailbox): + apply_on_local_node( + MailboxQuotaUpdate(mailbox), + "/run/coulobre-mail-apply.sock", + "mail node", + "mailbox quota update", + ) + + def create_local_account_backup(request): apply_on_local_node( request, diff --git a/src/coulobre/hosting/resource_requests.py b/src/coulobre/hosting/resource_requests.py index 811d033..b5cd920 100644 --- a/src/coulobre/hosting/resource_requests.py +++ b/src/coulobre/hosting/resource_requests.py @@ -4,7 +4,12 @@ from django.db.models import F from coulobre.mail_node import MailboxSpec -from .models import HostingAccount, HostingMailbox, HostingMailDomain +from .models import ( + HostingAccount, + HostingMailbox, + HostingMailDomain, + MailboxProvisioning, +) def lock_hosting_account(account_id, customer_id): @@ -69,3 +74,29 @@ def create_mailbox_request(account_id, local_part, *, customer_id=None): local_part=spec.local_part, quota_mib=plan.mailbox_quota_mib if plan is not None else None, ) + + +@transaction.atomic +def queue_mailbox_provisioning(mailbox): + lock_hosting_account(mailbox.mail_domain.account_id, customer_id=None) + MailboxProvisioning.objects.queue(mailbox=mailbox) + + +@transaction.atomic +def change_mailbox_quota(mailbox, quota_mib): + lock_hosting_account(mailbox.mail_domain.account_id, customer_id=None) + current = HostingMailbox.objects.get(pk=mailbox.pk) + if current.quota_mib == quota_mib: + return + + jobs = MailboxProvisioning.objects.filter(mailbox=current) + job = jobs.select_for_update().first() + if job is not None and job.state != "configured": + raise ValidationError( + "Complete the pending or failed mailbox request first." + ) + + current.quota_mib = quota_mib + current.save(update_fields=["quota_mib"]) + if job is not None: + MailboxProvisioning.objects.requeue(jobs, quota_update=True) diff --git a/src/coulobre/hosting/tasks.py b/src/coulobre/hosting/tasks.py index 485b3dd..9035b98 100644 --- a/src/coulobre/hosting/tasks.py +++ b/src/coulobre/hosting/tasks.py @@ -31,6 +31,7 @@ from .node_client import ( provision_local_database, provision_local_mailbox, publish_local_zone, + update_local_mailbox_quota, update_local_sftp, ) from .sftp import site_is_active @@ -275,7 +276,10 @@ def provision_mailbox(provisioning_id): def apply_mailbox_provisioning(provisioning): - provision_local_mailbox(provisioning.mailbox.spec) + if provisioning.quota_update: + update_local_mailbox_quota(provisioning.mailbox.spec) + else: + provision_local_mailbox(provisioning.mailbox.spec) @shared_task(acks_late=True, reject_on_worker_lost=True) diff --git a/src/coulobre/hosting/templates/hosting/account_detail.html b/src/coulobre/hosting/templates/hosting/account_detail.html index 64526dd..c846bb3 100644 --- a/src/coulobre/hosting/templates/hosting/account_detail.html +++ b/src/coulobre/hosting/templates/hosting/account_detail.html @@ -187,6 +187,9 @@
Download manifest + {% if change_mailbox_quota %} + Change storage limit + {% endif %} {% 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" %} diff --git a/src/coulobre/hosting/templates/hosting/mailbox_quota_form.html b/src/coulobre/hosting/templates/hosting/mailbox_quota_form.html new file mode 100644 index 0000000..92fcd9b --- /dev/null +++ b/src/coulobre/hosting/templates/hosting/mailbox_quota_form.html @@ -0,0 +1,21 @@ +{% extends "hosting/base.html" %} +{% block title %}Change mailbox storage limit · Coulobre Panel{% endblock %} +{% block content %} + ← {{ mailbox.mail_domain.account.name }} +
+
+

Change storage limit

+

{{ mailbox }}

+
+
+
+
+ {% csrf_token %} + {{ form.as_div }} +
+ + Cancel +
+
+
+{% endblock %} diff --git a/src/coulobre/hosting/test_mail_node_apply.py b/src/coulobre/hosting/test_mail_node_apply.py index 9451176..95beed2 100644 --- a/src/coulobre/hosting/test_mail_node_apply.py +++ b/src/coulobre/hosting/test_mail_node_apply.py @@ -11,7 +11,7 @@ from unittest.mock import patch from django.test import SimpleTestCase -from coulobre.mail_node import MailboxSpec, main +from coulobre.mail_node import MailboxQuotaUpdate, MailboxSpec, main from coulobre.mail_node_apply import ( apply_mailbox, check_dovecot_maildir, @@ -21,6 +21,7 @@ from coulobre.mail_node_apply import ( mailbox_status, run, ) +from coulobre.mail_node_quota import set_mailbox_quota class MailboxApplyRequestTests(SimpleTestCase): @@ -62,6 +63,20 @@ class MailboxApplyRequestTests(SimpleTestCase): self.assertEqual(reply["state"], "failed") self.apply.assert_not_called() + def test_quota_update_request_is_distinct_from_provisioning(self): + mailbox = MailboxSpec("example.net", "support", 256) + request = MailboxQuotaUpdate(mailbox) + with patch("coulobre.mail_node_quota.set_mailbox_quota") as change: + code, reply = self.request(request.manifest()) + + self.assertEqual(code, 0) + self.assertEqual( + reply, + request.manifest() | {"state": "configured", "problem": None}, + ) + change.assert_called_once_with(mailbox) + self.apply.assert_not_called() + class MailboxApplyTests(SimpleTestCase): def setUp(self): @@ -218,6 +233,46 @@ class MailboxApplyTests(SimpleTestCase): apply_mailbox(MailboxSpec("example.net", "support", quota_mib=128)) self.assertEqual(path.read_bytes(), original) + def test_quota_update_can_resume_after_the_dovecot_table_was_written(self): + path = apply_mailbox(self.spec) + credentials = json.loads(path.read_text()) + sibling = MailboxSpec("example.net", "other") + apply_mailbox(sibling) + sibling_row = next( + row + for row in self.users.read_text().splitlines() + if row.startswith(sibling.address + ":") + ) + self.postfix_lookup.return_value = "1" + limited = MailboxSpec("example.net", "support", quota_mib=128) + with ( + patch("coulobre.mail_node_quota.require_root_directory"), + patch("coulobre.mail_node_apply.check_dovecot_quota"), + patch("coulobre.mail_node_apply.wait_for_dovecot_user") as wait, + ): + wait.side_effect = ValueError( + "Dovecot has not read the new row yet." + ) + with self.assertRaisesMessage(ValueError, "new row yet"): + set_mailbox_quota(limited) + self.assertIn( + "userdb_quota_rule=*:bytes=128M", self.users.read_text() + ) + self.assertEqual(json.loads(path.read_text()), credentials) + + wait.side_effect = None + with self.assertRaisesMessage( + ValueError, "Retry the original update" + ): + set_mailbox_quota(MailboxSpec("example.net", "support", 256)) + set_mailbox_quota(limited) + + self.assertEqual( + json.loads(path.read_text()), + credentials | {"mailbox": limited.manifest()}, + ) + self.assertIn(sibling_row, self.users.read_text()) + def test_waits_for_dovecot_to_read_the_updated_authentication_file(self): home = self.storage / self.spec.domain / self.spec.local_part self.resolve_home.side_effect = [None, None, str(home)] diff --git a/src/coulobre/hosting/test_mailbox_provisioning.py b/src/coulobre/hosting/test_mailbox_provisioning.py index f749b0d..6b4a6cf 100644 --- a/src/coulobre/hosting/test_mailbox_provisioning.py +++ b/src/coulobre/hosting/test_mailbox_provisioning.py @@ -4,6 +4,7 @@ from django.contrib.auth import get_user_model from django.contrib.auth.models import Permission from django.test import TestCase, override_settings from django.urls import reverse +from django.utils import timezone from coulobre.mail_node import MailboxSpec @@ -121,3 +122,102 @@ class MailboxProvisioningTests(TestCase): job.refresh_from_db() self.assertEqual(job.state, "queued") self.assertFalse(job.problem) + + def allow_quota_changes(self, user): + user.user_permissions.add( + Permission.objects.get( + content_type__app_label="hosting", + codename="change_hostingmailbox", + ) + ) + + def test_quota_edit_queues_an_update_for_a_configured_mailbox(self): + self.allow_quota_changes(self.operator) + job = MailboxProvisioning.objects.create( + mailbox=self.mailbox, finished_at=timezone.now() + ) + quota_url = reverse("panel:mailbox_quota", args=[self.mailbox.pk]) + self.assertContains( + self.client.get(self.detail), "Change storage limit" + ) + self.assertRedirects( + self.client.post(quota_url, {"quota_mib": 384}), self.detail + ) + + self.mailbox.refresh_from_db() + self.assertEqual(self.mailbox.quota_mib, 384) + job.refresh_from_db() + self.assertEqual(job.state, "queued") + self.assertTrue(job.quota_update) + with ( + patch( + "coulobre.hosting.tasks.update_local_mailbox_quota" + ) as update, + patch("coulobre.hosting.tasks.provision_local_mailbox") as install, + ): + provision_mailbox.run(job.pk) + update.assert_called_once_with( + MailboxSpec("site.example", "support", 384) + ) + install.assert_not_called() + job.refresh_from_db() + self.assertEqual(job.state, "configured") + + def test_failed_quota_update_keeps_the_target_for_retry(self): + self.allow_quota_changes(self.operator) + job = MailboxProvisioning.objects.create( + mailbox=self.mailbox, finished_at=timezone.now() + ) + quota_url = reverse("panel:mailbox_quota", args=[self.mailbox.pk]) + self.client.post(quota_url, {"quota_mib": 384}) + with patch( + "coulobre.hosting.tasks.update_local_mailbox_quota", + side_effect=OSError, + ): + provision_mailbox.run(job.pk) + + blocked = self.client.post(quota_url, {"quota_mib": 128}) + self.assertContains( + blocked, "Complete the pending or failed mailbox request first." + ) + self.assertEqual( + HostingMailbox.objects.get(pk=self.mailbox.pk).quota_mib, 384 + ) + self.assertRedirects(self.client.post(self.url), self.detail) + with patch( + "coulobre.hosting.tasks.update_local_mailbox_quota" + ) as update: + provision_mailbox.run(job.pk) + update.assert_called_once_with( + MailboxSpec("site.example", "support", 384) + ) + + @override_settings(LOCAL_MAILBOX_PROVISIONING=False) + def test_separate_mail_node_quota_edit_is_saved_in_the_manifest(self): + self.allow_quota_changes(self.operator) + quota_url = reverse("panel:mailbox_quota", args=[self.mailbox.pk]) + manifest_url = reverse( + "panel:mailbox_manifest", args=[self.mailbox.pk] + ) + self.assertRedirects( + self.client.post(quota_url, {"quota_mib": 256}), self.detail + ) + self.assertEqual( + self.client.get(manifest_url).json()["quota_mib"], 256 + ) + self.assertRedirects( + self.client.post(quota_url, {"quota_mib": ""}), self.detail + ) + self.assertEqual(self.client.get(manifest_url).json()["version"], 1) + self.assertFalse(MailboxProvisioning.objects.exists()) + + def test_reseller_cannot_edit_quota_even_with_mailbox_permissions(self): + self.allow_quota_changes(self.reseller) + self.client.force_login(self.reseller) + quota_url = reverse("panel:mailbox_quota", args=[self.mailbox.pk]) + self.assertEqual( + self.client.post(quota_url, {"quota_mib": 128}).status_code, 403 + ) + self.assertNotContains( + self.client.get(self.detail), "Change storage limit" + ) diff --git a/src/coulobre/hosting/urls.py b/src/coulobre/hosting/urls.py index c6eb71d..fea27c2 100644 --- a/src/coulobre/hosting/urls.py +++ b/src/coulobre/hosting/urls.py @@ -106,6 +106,11 @@ urlpatterns = [ views.DownloadMailboxManifest.as_view(), name="mailbox_manifest", ), + path( + "mailboxes//quota/", + views.MailboxQuotaEdit.as_view(), + name="mailbox_quota", + ), path( "mailboxes//provision/", views.RequestMailboxProvisioning.as_view(), diff --git a/src/coulobre/hosting/views.py b/src/coulobre/hosting/views.py index fc94ba9..db773c6 100644 --- a/src/coulobre/hosting/views.py +++ b/src/coulobre/hosting/views.py @@ -54,14 +54,18 @@ from .models import ( HostingDnsZone, HostingMailbox, HostingPlan, - MailboxProvisioning, Reseller, WebActivation, WebHTTPS, WebProvisioningPlan, ) from .reseller_accounts import create_reseller_account -from .resource_requests import create_database_request, create_mailbox_request +from .resource_requests import ( + change_mailbox_quota, + create_database_request, + create_mailbox_request, + queue_mailbox_provisioning, +) from .sftp import ( SFTPKeyUploadForm, can_manage_sftp, @@ -98,6 +102,7 @@ PROVISION_MAILBOX = ( VIEW_MAILBOXES, "hosting.add_mailboxprovisioning", ) +CHANGE_MAILBOX_QUOTA = (*PROVISION_MAILBOX, "hosting.change_hostingmailbox") class AccountList(TenantScopeMixin, PermissionRequiredMixin, ListView): @@ -311,6 +316,9 @@ class AccountDetail(TenantScopeMixin, PermissionRequiredMixin, DetailView): context["local_mailbox_enabled"] = ( settings.LOCAL_MAILBOX_PROVISIONING ) + context["change_mailbox_quota"] = user.has_perms( + CHANGE_MAILBOX_QUOTA + ) context["mailboxes"] = mailboxes return context @@ -801,6 +809,29 @@ class DownloadMailboxManifest( ) +class MailboxQuotaEdit(OperatorOnlyMixin, PermissionRequiredMixin, UpdateView): + queryset = HostingMailbox.objects.select_related("mail_domain__account") + permission_required = CHANGE_MAILBOX_QUOTA + fields = ("quota_mib",) + template_name = "hosting/mailbox_quota_form.html" + context_object_name = "mailbox" + + def get_form(self, form_class=None): + form = super().get_form(form_class) + form.fields[ + "quota_mib" + ].help_text = "Leave blank for unlimited storage." + return form + + def form_valid(self, form): + try: + change_mailbox_quota(self.object, form.cleaned_data["quota_mib"]) + except ValidationError as error: + form.add_error(None, error) + return self.form_invalid(form) + return redirect(self.object.mail_domain.account) + + class RequestMailboxProvisioning( OperatorOnlyMixin, PermissionRequiredMixin, View ): @@ -813,7 +844,7 @@ class RequestMailboxProvisioning( HostingMailbox.objects.select_related("mail_domain__account"), pk=pk, ) - MailboxProvisioning.objects.queue(mailbox=mailbox) + queue_mailbox_provisioning(mailbox) return redirect(mailbox.mail_domain.account) diff --git a/src/coulobre/mail_node.py b/src/coulobre/mail_node.py index 741bc0b..68b9c93 100644 --- a/src/coulobre/mail_node.py +++ b/src/coulobre/mail_node.py @@ -92,6 +92,35 @@ class MailboxSpec: return cls(data["domain"], data["local_part"], data.get("quota_mib")) +@dataclass(frozen=True) +class MailboxQuotaUpdate: + mailbox: MailboxSpec + + def manifest(self): + return {"operation": "set_quota", "mailbox": self.mailbox.manifest()} + + +def parse_mailbox_request(data): + if ( + isinstance(data, dict) + and data.keys() == {"operation", "mailbox"} + and data["operation"] == "set_quota" + ): + return MailboxQuotaUpdate(MailboxSpec.from_manifest(data["mailbox"])) + return MailboxSpec.from_manifest(data) + + +def apply_mailbox_request(request): + if isinstance(request, MailboxQuotaUpdate): + from .mail_node_quota import set_mailbox_quota + + set_mailbox_quota(request.mailbox) + else: + from .mail_node_apply import apply_mailbox + + apply_mailbox(request) + + def main(argv=None): parser = argparse.ArgumentParser(prog="coulobre-mail-node") commands = parser.add_subparsers(dest="command", required=True) @@ -103,6 +132,10 @@ def main(argv=None): "apply", help="Install a virtual mailbox on the mail node." ) apply.add_argument("manifest", type=Path) + quota = commands.add_parser( + "set-quota", help="Change the storage limit of an installed mailbox." + ) + quota.add_argument("manifest", type=Path) commands.add_parser( "apply-request", help="Apply one mailbox manifest from standard input and report JSON.", @@ -124,10 +157,8 @@ def main(argv=None): args = parser.parse_args(argv) if args.command == "apply-request": - from .mail_node_apply import apply_mailbox - return serve_apply_request( - MANIFEST_VERSION, MailboxSpec.from_manifest, apply_mailbox + MANIFEST_VERSION, parse_mailbox_request, apply_mailbox_request ) try: @@ -139,6 +170,19 @@ def main(argv=None): credentials = apply_mailbox(mailbox) print(f"Applied virtual mailbox {mailbox.address}.") print(f"Credentials file {credentials}") + elif args.command == "set-quota": + from .mail_node_quota import set_mailbox_quota + + set_mailbox_quota(mailbox) + print( + json.dumps( + { + "address": mailbox.address, + "quota_mib": mailbox.quota_mib, + }, + indent=2, + ) + ) elif args.command == "status": from .mail_node_apply import mailbox_status diff --git a/src/coulobre/mail_node_apply.py b/src/coulobre/mail_node_apply.py index 539201b..336c826 100644 --- a/src/coulobre/mail_node_apply.py +++ b/src/coulobre/mail_node_apply.py @@ -50,15 +50,20 @@ class Credentials: def home_marker(self): return self.path.with_suffix(".home-ready") - def save(self): + def save(self, *, replace=False): document = { "mailbox": self.mailbox.manifest(), "password": self.password, "password_hash": self.password_hash, } - write_new_file( - self.path, json.dumps(document, indent=2) + "\n", mode=0o600 - ) + text = json.dumps(document, indent=2) + "\n" + if replace: + with TemporaryDirectory(dir=self.path.parent) as scratch: + staged = Path(scratch) / "credentials" + write_new_file(staged, text, mode=0o600) + os.replace(staged, self.path) + else: + write_new_file(self.path, text, mode=0o600) def credential_path(mailbox): @@ -103,7 +108,7 @@ def apply_mailbox(mailbox): @contextmanager -def locked_state(*, create): +def locked_state(*, create, exclusive=False): try: require_root_directory( STATE_DIRECTORY, create_mode=0o700 if create else None @@ -117,7 +122,9 @@ def locked_state(*, create): yield None return try: - fcntl.flock(directory, fcntl.LOCK_EX if create else fcntl.LOCK_SH) + fcntl.flock( + directory, fcntl.LOCK_EX if create or exclusive else fcntl.LOCK_SH + ) yield directory finally: os.close(directory) @@ -305,20 +312,26 @@ def lookup_tables(records, account, auth_group, *, modern): def dovecot_lookup_rows(records, account, *, modern): - rows = set() - for record in records: - row = ( - f"{record.mailbox.address}:{record.password_hash}:" - f"{account.pw_uid}:{account.pw_gid}::{record.home}::" - ) - if record.mailbox.quota_mib is not None: - key, value = quota_userdb_setting(record.mailbox, modern) - row += f"userdb_{key}={value}" - rows.add(row) - return rows + return { + dovecot_lookup_row(record, account, modern=modern) + for record in records + } + + +def dovecot_lookup_row(record, account, *, modern): + row = ( + f"{record.mailbox.address}:{record.password_hash}:" + f"{account.pw_uid}:{account.pw_gid}::{record.home}::" + ) + if record.mailbox.quota_mib is not None: + key, value = quota_userdb_setting(record.mailbox, modern) + row += f"userdb_{key}={value}" + return row def quota_userdb_setting(mailbox, modern): + if mailbox.quota_mib is None: + return ("quota_storage_size" if modern else "quota_rule"), "" size = f"{mailbox.quota_mib}M" if modern: return "quota_storage_size", size @@ -532,19 +545,21 @@ def postfix_lookup(key, path): ) -def dovecot_quota_matches(mailbox, modern): - if mailbox.quota_mib is None: +def dovecot_quota_matches(mailbox, modern, *, verify_unlimited=False): + if mailbox.quota_mib is None and not verify_unlimited: return True key, value = quota_userdb_setting(mailbox, modern) return run("doveadm", "user", "-f", key, mailbox.address) == value -def wait_for_dovecot_user(mailbox, home, modern): +def wait_for_dovecot_user(mailbox, home, modern, *, verify_unlimited=False): # Dovecot checks for passwd-file changes at most once per second. for _ in range(10): resolved = dovecot_home(mailbox) if resolved == str(home): - if dovecot_quota_matches(mailbox, modern): + if dovecot_quota_matches( + mailbox, modern, verify_unlimited=verify_unlimited + ): return elif resolved is not None: break diff --git a/src/coulobre/mail_node_quota.py b/src/coulobre/mail_node_quota.py new file mode 100644 index 0000000..aa37c17 --- /dev/null +++ b/src/coulobre/mail_node_quota.py @@ -0,0 +1,78 @@ +import os +from dataclasses import replace + +from . import mail_node_apply as mail +from .node_files import require_root_directory + + +def set_mailbox_quota(mailbox): + if os.geteuid() != 0: + raise ValueError("Run set-quota as root on the mail node.") + with mail.locked_state(create=False, exclusive=True) as state_directory: + path = mail.credential_path(mailbox) + if state_directory is None or not os.path.lexists(path): + raise ValueError( + "Apply the mailbox manifest before changing its quota." + ) + original = mail.load_credentials(path) + updated = replace(original, mailbox=mailbox) + publish_mailbox_quota(original, updated) + if original != updated: + updated.save(replace=True) + os.fsync(state_directory) + + +def publish_mailbox_quota(original, updated): + mailbox = updated.mailbox + for directory in ( + mail.DOVECOT_USERS.parent, + mail.POSTFIX_MAILBOXES.parent, + ): + require_root_directory(directory) + account, auth_group, modern = mail.check_services(mailbox) + if not mail.home_is_prepared(original): + raise ValueError( + "Complete mailbox provisioning before changing its quota." + ) + mail.ensure_mail_directory(mail.MAIL_ROOT, create=False) + mail.ensure_mail_directory(original.home.parent, create=False) + mail.ensure_mail_home(original.home, account, create=False) + if ( + mail.postfix_lookup(mailbox.domain, mail.POSTFIX_DOMAINS) != "1" + or mail.postfix_lookup(mailbox.address, mail.POSTFIX_MAILBOXES) != "1" + ): + raise ValueError( + "Postfix did not resolve the managed domain and recipient." + ) + if mailbox.quota_mib is not None: + mail.check_dovecot_quota(modern) + + contents = mail.read_lookup_table(mail.DOVECOT_USERS, 0o640, auth_group) + if not contents.startswith(mail.MANAGED_HEADER): + raise ValueError("Expected a managed Dovecot lookup table.") + rows = contents.removeprefix(mail.MANAGED_HEADER).splitlines() + old_row = mail.dovecot_lookup_row(original, account, modern=modern) + new_row = mail.dovecot_lookup_row(updated, account, modern=modern) + matched = [ + index + for index, row in enumerate(rows) + if row.startswith(mailbox.address + ":") + ] + if len(matched) != 1 or rows[matched[0]] not in (old_row, new_row): + raise ValueError( + "The Dovecot entry conflicts with this quota update. " + "Retry the original update if it was interrupted." + ) + rows[matched[0]] = new_row + mail.publish_table(mail.DOVECOT_USERS, (0o640, auth_group, rows), contents) + # Persist the live table before updating the registry. + directory = os.open( + mail.DOVECOT_USERS.parent, os.O_RDONLY | os.O_DIRECTORY + ) + try: + os.fsync(directory) + finally: + os.close(directory) + mail.wait_for_dovecot_user( + mailbox, original.home, modern, verify_unlimited=True + )