diff --git a/deploy/dovecot/coulobre-2.4.conf.example b/deploy/dovecot/coulobre-2.4.conf.example
index f6f4526..3f3d06a 100644
--- a/deploy/dovecot/coulobre-2.4.conf.example
+++ b/deploy/dovecot/coulobre-2.4.conf.example
@@ -8,6 +8,17 @@ ssl_server_key_file = /etc/ssl/coulobre-mail/privkey.pem
mail_driver = maildir
mail_path = ~/Maildir
+mail_plugins {
+ quota = yes
+}
+protocol imap {
+ mail_plugins {
+ imap_quota = yes
+ }
+}
+quota_storage_grace = 0
+quota "User quota" {
+}
# Set both values to the UID of coulobre-vmail.
first_valid_uid = 103
last_valid_uid = 103
diff --git a/docs/deployment.md b/docs/deployment.md
index 8d346a8..7b694d6 100644
--- a/docs/deployment.md
+++ b/docs/deployment.md
@@ -478,6 +478,10 @@ The initial password stays in the root-only credentials file on the mail node.
To locate that file, download the manifest and use the node's `apply` command.
Reapplying the manifest preserves the password and prints the file path.
+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)
+
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 0c2120f..ca8361c 100644
--- a/docs/development.md
+++ b/docs/development.md
@@ -30,9 +30,14 @@ plan have unlimited requests. The account page shows usage for configured
limits. Mailboxes count toward the same limit across all of an account's mail
domains, including domains retained after a primary domain change.
+Set **Mailbox storage limit (MiB)** to assign a Dovecot storage quota to each
+new mailbox requested under the plan. The account page shows each mailbox's
+assigned limit. Leave the field blank to omit a Coulobre storage limit.
+[Configure Dovecot quota enforcement](#enforce-mailbox-storage-limits)
+
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.
+requests of that type. Storage limit changes apply to new mailbox requests.
## Give a reseller access to assigned accounts
@@ -363,6 +368,8 @@ Existing mailbox requests keep their addresses when the primary domain changes.
The **Mailbox requests** table shows the email addresses. Operators can
download a versioned manifest that contains the domain and local part.
Resellers can see mailbox requests on their assigned accounts.
+Version 2 adds `quota_mib` for mailboxes with a storage limit. Version 1
+manifests continue to apply with no Coulobre storage limit.
Run the installed node command to validate the manifest and display its
address. The manifest describes a virtual user for the Postfix and Dovecot
@@ -448,6 +455,37 @@ For an existing mail node, follow the
[Dovecot upgrade guide](https://doc.dovecot.org/2.4.2/installation/upgrade/2.3-to-2.4.html)
to migrate its configuration and retain its Maildirs and Coulobre registry.
+#### Enforce mailbox storage limits
+
+Use Dovecot's count quota driver for mailbox storage limits. The
+[Dovecot 2.4 example](../deploy/dovecot/coulobre-2.4.conf.example) enables
+quota enforcement and reports usage to IMAP clients. Keep the quota's default
+storage size unlimited so mailbox-specific limits come from Coulobre.
+[Dovecot 2.4 quota configuration](https://doc.dovecot.org/2.4.2/core/plugins/quota.html)
+
+On Dovecot 2.3, merge these settings into the mail node configuration.
+
+```text
+mail_plugins = $mail_plugins quota
+protocol imap {
+ mail_plugins = $mail_plugins imap_quota
+}
+plugin {
+ quota = count:User quota
+ quota_vsizes = yes
+ quota_grace = 0
+}
+```
+
+Reload Dovecot after updating its configuration. The examples disable the
+delivery grace allowance so LMTP and IMAP enforce the assigned limit. To
+see the usage and limit of a live mailbox, run
+`sudo doveadm quota get -u support@example.net`.
+[Dovecot 2.3 quota configuration](https://doc.dovecot.org/2.3/configuration_manual/quota/)
+
+After upgrading a mail node from Dovecot 2.3 to 2.4, reapply a managed mailbox
+manifest to republish the lookup table with the new quota setting syntax.
+
#### Install the mailbox
Start Postfix first to initialize its spool directory, then start Dovecot so
@@ -535,7 +573,7 @@ sudo systemctl enable --now coulobre-mail-apply.socket
```
Grant the socket group only to the service identity responsible for mailbox
-provisioning. Send one version 1 mailbox manifest as UTF-8 JSON to
+provisioning. Send one version 1 or 2 mailbox manifest as UTF-8 JSON to
`/run/coulobre-mail-apply.sock`, with a limit of 4 KiB. Shut down the writing
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`.
diff --git a/src/coulobre/hosting/admin.py b/src/coulobre/hosting/admin.py
index 75ac3f6..95d7887 100644
--- a/src/coulobre/hosting/admin.py
+++ b/src/coulobre/hosting/admin.py
@@ -46,7 +46,13 @@ class HostingAccountAdmin(admin.ModelAdmin):
@admin.register(HostingPlan)
class HostingPlanAdmin(admin.ModelAdmin):
- list_display = ("name", "description", "database_limit", "mailbox_limit")
+ list_display = (
+ "name",
+ "description",
+ "database_limit",
+ "mailbox_limit",
+ "mailbox_quota_mib",
+ )
search_fields = ("name",)
def save_model(self, request, obj, form, change):
diff --git a/src/coulobre/hosting/migrations/0021_mailbox_storage_limits.py b/src/coulobre/hosting/migrations/0021_mailbox_storage_limits.py
new file mode 100644
index 0000000..adf82ff
--- /dev/null
+++ b/src/coulobre/hosting/migrations/0021_mailbox_storage_limits.py
@@ -0,0 +1,43 @@
+# Generated by Django 5.2.19 on 2026-11-21 11:56
+
+import django.core.validators
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("hosting", "0020_account_backup_job"),
+ ]
+
+ operations = [
+ migrations.AddField(
+ model_name="hostingmailbox",
+ name="quota_mib",
+ field=models.PositiveIntegerField(
+ blank=True,
+ null=True,
+ validators=[
+ django.core.validators.MinValueValidator(1),
+ django.core.validators.MaxValueValidator(2147483647),
+ ],
+ verbose_name="storage limit (MiB)",
+ ),
+ ),
+ migrations.AddField(
+ model_name="hostingplan",
+ name="mailbox_quota_mib",
+ field=models.PositiveIntegerField(
+ blank=True,
+ help_text=(
+ "Applies to new mailbox requests. "
+ "Leave blank for unlimited."
+ ),
+ null=True,
+ validators=[
+ django.core.validators.MinValueValidator(1),
+ django.core.validators.MaxValueValidator(2147483647),
+ ],
+ verbose_name="mailbox storage limit (MiB)",
+ ),
+ ),
+ ]
diff --git a/src/coulobre/hosting/models.py b/src/coulobre/hosting/models.py
index 8f12bd8..18d5041 100644
--- a/src/coulobre/hosting/models.py
+++ b/src/coulobre/hosting/models.py
@@ -1,7 +1,11 @@
import uuid
from django.conf import settings
-from django.core.validators import RegexValidator
+from django.core.validators import (
+ MaxValueValidator,
+ MinValueValidator,
+ RegexValidator,
+)
from django.db import models
from django.urls import reverse
from django.utils import timezone
@@ -19,7 +23,11 @@ from coulobre.dns_node import (
MxRecord,
TxtRecord,
)
-from coulobre.mail_node import LOCAL_PART_MAX_LENGTH, MailboxSpec
+from coulobre.mail_node import (
+ LOCAL_PART_MAX_LENGTH,
+ MAX_MAILBOX_QUOTA_MIB,
+ MailboxSpec,
+)
from .fields import DomainNameField
@@ -128,6 +136,18 @@ class HostingPlan(models.Model):
"Leave blank for unlimited. Enter 0 to block new mailbox requests."
),
)
+ mailbox_quota_mib = models.PositiveIntegerField(
+ "mailbox storage limit (MiB)",
+ blank=True,
+ null=True,
+ validators=[
+ MinValueValidator(1),
+ MaxValueValidator(MAX_MAILBOX_QUOTA_MIB),
+ ],
+ help_text=(
+ "Applies to new mailbox requests. Leave blank for unlimited."
+ ),
+ )
class Meta:
ordering = ("name", "pk")
@@ -252,6 +272,15 @@ class HostingMailbox(models.Model):
HostingMailDomain, on_delete=models.PROTECT, related_name="mailboxes"
)
local_part = models.CharField(max_length=LOCAL_PART_MAX_LENGTH)
+ quota_mib = models.PositiveIntegerField(
+ "storage limit (MiB)",
+ blank=True,
+ null=True,
+ validators=[
+ MinValueValidator(1),
+ MaxValueValidator(MAX_MAILBOX_QUOTA_MIB),
+ ],
+ )
class Meta:
ordering = ("mail_domain__domain", "local_part")
@@ -267,7 +296,9 @@ class HostingMailbox(models.Model):
@property
def spec(self):
- return MailboxSpec(self.mail_domain.domain, self.local_part)
+ return MailboxSpec(
+ self.mail_domain.domain, self.local_part, self.quota_mib
+ )
class WebProvisioningPlan(models.Model):
diff --git a/src/coulobre/hosting/resource_requests.py b/src/coulobre/hosting/resource_requests.py
index 33884b3..811d033 100644
--- a/src/coulobre/hosting/resource_requests.py
+++ b/src/coulobre/hosting/resource_requests.py
@@ -65,4 +65,7 @@ def create_mailbox_request(account_id, local_part, *, customer_id=None):
raise ValidationError(
"This hosting account has reached its mailbox limit."
)
- return mail_domain.mailboxes.create(local_part=spec.local_part)
+ return mail_domain.mailboxes.create(
+ local_part=spec.local_part,
+ quota_mib=plan.mailbox_quota_mib if plan is not None else None,
+ )
diff --git a/src/coulobre/hosting/templates/hosting/account_detail.html b/src/coulobre/hosting/templates/hosting/account_detail.html
index 5fcfbca..64526dd 100644
--- a/src/coulobre/hosting/templates/hosting/account_detail.html
+++ b/src/coulobre/hosting/templates/hosting/account_detail.html
@@ -174,6 +174,7 @@
| Email address |
+ Storage limit |
{% if is_operator %}Deployment | {% endif %}
@@ -181,6 +182,7 @@
{% for mailbox in mailboxes %}
| {{ mailbox }} |
+ {% if mailbox.quota_mib is not None %}{{ mailbox.quota_mib }} MiB{% else %}Unlimited{% endif %} |
{% if is_operator %}
diff --git a/src/coulobre/hosting/templates/hosting/hosting_plan_list.html b/src/coulobre/hosting/templates/hosting/hosting_plan_list.html
index 9bf7016..080c886 100644
--- a/src/coulobre/hosting/templates/hosting/hosting_plan_list.html
+++ b/src/coulobre/hosting/templates/hosting/hosting_plan_list.html
@@ -17,6 +17,7 @@
| Description |
Database limit |
Mailbox limit |
+ Storage per new mailbox |
@@ -32,6 +33,7 @@
{{ hosting_plan.description|default:"—" }} |
{{ hosting_plan.database_limit|default_if_none:"Unlimited" }} |
{{ hosting_plan.mailbox_limit|default_if_none:"Unlimited" }} |
+ {% if hosting_plan.mailbox_quota_mib is not None %}{{ hosting_plan.mailbox_quota_mib }} MiB{% else %}Unlimited{% endif %} |
{% endfor %}
diff --git a/src/coulobre/hosting/test_hosting_plans.py b/src/coulobre/hosting/test_hosting_plans.py
index 7ba51c8..72b0afe 100644
--- a/src/coulobre/hosting/test_hosting_plans.py
+++ b/src/coulobre/hosting/test_hosting_plans.py
@@ -35,12 +35,15 @@ class HostingPlanTests(TestCase):
"description": "Shared hosting for small sites",
"database_limit": 0,
"mailbox_limit": 5,
+ "mailbox_quota_mib": 256,
},
)
self.assertRedirects(response, list_url)
plan = HostingPlan.objects.get()
self.assertEqual(plan.database_limit, 0)
self.assertEqual(plan.mailbox_limit, 5)
+ self.assertEqual(plan.mailbox_quota_mib, 256)
+ self.assertContains(self.client.get(list_url), "256 MiB")
self.assertContains(
self.client.get(self.account.get_absolute_url()), "Unassigned"
@@ -64,12 +67,14 @@ class HostingPlanTests(TestCase):
"description": "Updated description",
"database_limit": "",
"mailbox_limit": 2,
+ "mailbox_quota_mib": "",
},
)
self.assertRedirects(response, list_url)
plan.refresh_from_db()
self.assertIsNone(plan.database_limit)
self.assertEqual(plan.mailbox_limit, 2)
+ self.assertIsNone(plan.mailbox_quota_mib)
self.assertContains(self.client.get(list_url), "Unlimited")
self.assertContains(
self.client.get(reverse("panel:accounts")), "Standard"
@@ -95,10 +100,12 @@ class HostingPlanTests(TestCase):
"name": "Invalid plan",
"database_limit": -1,
"mailbox_limit": -2,
+ "mailbox_quota_mib": 0,
},
)
self.assertIn("database_limit", response.context["form"].errors)
self.assertIn("mailbox_limit", response.context["form"].errors)
+ self.assertIn("mailbox_quota_mib", response.context["form"].errors)
self.assertFalse(HostingPlan.objects.exists())
def test_editor_without_plan_permission_cannot_assign_in_either_interface(
diff --git a/src/coulobre/hosting/test_mail_node_apply.py b/src/coulobre/hosting/test_mail_node_apply.py
index 9f3e001..9451176 100644
--- a/src/coulobre/hosting/test_mail_node_apply.py
+++ b/src/coulobre/hosting/test_mail_node_apply.py
@@ -15,6 +15,7 @@ from coulobre.mail_node import MailboxSpec, main
from coulobre.mail_node_apply import (
apply_mailbox,
check_dovecot_maildir,
+ check_dovecot_quota,
credential_path,
ensure_mail_home,
mailbox_status,
@@ -97,10 +98,10 @@ class MailboxApplyTests(SimpleTestCase):
)
)
self.account = SimpleNamespace(pw_uid=1001, pw_gid=1001)
- self.enterContext(
+ self.services = self.enterContext(
patch(
"coulobre.mail_node_apply.check_services",
- return_value=(self.account, os.getegid()),
+ return_value=(self.account, os.getegid(), False),
)
)
self.resolve_home = self.enterContext(
@@ -171,6 +172,52 @@ class MailboxApplyTests(SimpleTestCase):
self.assertEqual(credential_file.read_bytes(), original)
self.assertIn("support@example.net\t1", self.mailboxes.read_text())
+ def test_reapplying_after_dovecot_upgrade_rewrites_managed_quota_settings(
+ self,
+ ):
+ mailbox = MailboxSpec("example.net", "support", quota_mib=128)
+ with (
+ patch("coulobre.mail_node_apply.check_dovecot_quota"),
+ patch(
+ "coulobre.mail_node_apply.dovecot_quota_matches",
+ return_value=True,
+ ),
+ ):
+ path = apply_mailbox(mailbox)
+ original = path.read_bytes()
+ self.assertIn(
+ "userdb_quota_rule=*:bytes=128M", self.users.read_text()
+ )
+ self.services.return_value = (self.account, os.getegid(), True)
+ self.assertEqual(apply_mailbox(mailbox), path)
+
+ self.assertEqual(path.read_bytes(), original)
+ self.assertIn("userdb_quota_storage_size=128M", self.users.read_text())
+ self.assertNotIn("userdb_quota_rule", self.users.read_text())
+
+ def test_dovecot_quota_configuration_is_required_before_provisioning(self):
+ mailbox = MailboxSpec("example.net", "support", quota_mib=128)
+ with (
+ patch(
+ "coulobre.mail_node_apply.check_dovecot_quota",
+ side_effect=ValueError("Enable quota"),
+ ),
+ self.assertRaisesMessage(ValueError, "Enable quota"),
+ ):
+ apply_mailbox(mailbox)
+
+ self.assertFalse(credential_path(mailbox).exists())
+ self.assertFalse(self.mailboxes.exists())
+
+ def test_reapplying_with_a_different_quota_keeps_the_registered_mailbox(
+ self,
+ ):
+ path = apply_mailbox(self.spec)
+ original = path.read_bytes()
+ with self.assertRaisesMessage(ValueError, "registered storage limit"):
+ apply_mailbox(MailboxSpec("example.net", "support", quota_mib=128))
+ self.assertEqual(path.read_bytes(), original)
+
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)]
@@ -323,6 +370,34 @@ class MailboxCommandTests(SimpleTestCase):
):
check_dovecot_maildir()
+ def test_dovecot_24_accepts_a_globally_enabled_quota_plugin(self):
+ with patch(
+ "coulobre.mail_node_apply.run",
+ side_effect=[
+ 'quota "User quota" {\n}',
+ "quota = yes",
+ "imap_quota = yes",
+ "yes",
+ "quota = yes",
+ "yes",
+ ],
+ ):
+ check_dovecot_quota(modern=True)
+
+ def test_dovecot_24_rejects_explicitly_disabled_quota(self):
+ with (
+ patch(
+ "coulobre.mail_node_apply.run",
+ side_effect=[
+ 'quota "User quota" {\n}',
+ "quota = yes",
+ "quota = no",
+ ],
+ ),
+ self.assertRaisesMessage(ValueError, "quota enforcement"),
+ ):
+ check_dovecot_quota(modern=True)
+
def test_dovecot_23_checks_the_legacy_maildir_setting(self):
with patch(
"coulobre.mail_node_apply.run",
diff --git a/src/coulobre/hosting/test_mail_node_backup.py b/src/coulobre/hosting/test_mail_node_backup.py
index be7f183..b76da63 100644
--- a/src/coulobre/hosting/test_mail_node_backup.py
+++ b/src/coulobre/hosting/test_mail_node_backup.py
@@ -106,6 +106,20 @@ class MailboxBackupTests(SimpleTestCase):
self.assertFalse((self.home / "Maildir").exists())
+ def test_legacy_archive_can_restore_to_a_mailbox_with_a_storage_limit(
+ self,
+ ):
+ self.make_archive()
+ limited = MailboxSpec(
+ self.mailbox.domain, self.mailbox.local_part, 128
+ )
+
+ mail_node_backup.restore_mailbox(limited, self.archive)
+
+ self.assertEqual(
+ (self.home / "Maildir/new/first").read_bytes(), MESSAGE
+ )
+
def test_corrupt_backup_leaves_no_restored_maildir(self):
self.make_archive()
self.archive.write_bytes(self.archive.read_bytes()[:-4])
diff --git a/src/coulobre/hosting/test_mailboxes.py b/src/coulobre/hosting/test_mailboxes.py
index c0ed21e..4690fa6 100644
--- a/src/coulobre/hosting/test_mailboxes.py
+++ b/src/coulobre/hosting/test_mailboxes.py
@@ -97,6 +97,36 @@ class MailboxRequestTests(TestCase):
)
self.assertEqual(HostingMailbox.objects.count(), 2)
+ def test_mailbox_storage_limit_is_captured_when_requested(self):
+ plan = HostingPlan.objects.create(name="Mail", mailbox_quota_mib=128)
+ HostingAccount.objects.filter(pk=self.account.pk).update(
+ hosting_plan=plan
+ )
+ original = self.request_mailbox("support")
+ HostingPlan.objects.filter(pk=plan.pk).update(mailbox_quota_mib=256)
+
+ self.assertRedirects(
+ self.client.post(self.request_url, {"local_part": "billing"}),
+ self.account.get_absolute_url(),
+ )
+
+ original.refresh_from_db()
+ self.assertEqual(original.quota_mib, 128)
+ self.assertEqual(
+ HostingMailbox.objects.get(local_part="billing").quota_mib, 256
+ )
+ response = self.client.get(
+ reverse("panel:mailbox_manifest", args=[original.pk])
+ )
+ self.assertEqual(response.json()["version"], 2)
+ self.assertEqual(response.json()["quota_mib"], 128)
+ self.assertEqual(
+ MailboxSpec.from_manifest(response.json()), original.spec
+ )
+ page = self.client.get(self.account.get_absolute_url())
+ self.assertContains(page, "128 MiB")
+ self.assertContains(page, "256 MiB")
+
def test_invalid_request_leaves_the_domain_available(self):
response = self.client.post(
self.request_url, {"local_part": "support+tag"}
@@ -250,3 +280,9 @@ class MailboxManifestTests(SimpleTestCase):
):
with self.subTest(change=change), self.assertRaises(ValueError):
MailboxSpec.from_manifest(manifest | change)
+
+ def test_quota_manifest_requires_a_positive_integer_limit(self):
+ manifest = MailboxSpec("example.net", "support", 128).manifest()
+ for size in (None, False, 0, -1, "128", 2**31):
+ with self.subTest(size=size), self.assertRaises(ValueError):
+ MailboxSpec.from_manifest(manifest | {"quota_mib": size})
diff --git a/src/coulobre/hosting/views.py b/src/coulobre/hosting/views.py
index 9fb6ce8..fc94ba9 100644
--- a/src/coulobre/hosting/views.py
+++ b/src/coulobre/hosting/views.py
@@ -827,7 +827,13 @@ class HostingPlanList(OperatorOnlyMixin, PermissionRequiredMixin, ListView):
class HostingPlanEditor:
model = HostingPlan
- fields = ("name", "description", "database_limit", "mailbox_limit")
+ fields = (
+ "name",
+ "description",
+ "database_limit",
+ "mailbox_limit",
+ "mailbox_quota_mib",
+ )
template_name = "hosting/hosting_plan_form.html"
success_url = reverse_lazy("panel:hosting_plans")
diff --git a/src/coulobre/mail_node.py b/src/coulobre/mail_node.py
index 964af3a..741bc0b 100644
--- a/src/coulobre/mail_node.py
+++ b/src/coulobre/mail_node.py
@@ -8,8 +8,10 @@ from .domain_names import canonical_domain
from .node_requests import serve_apply_request
MANIFEST_VERSION = 1
+QUOTA_MANIFEST_VERSION = 2
MANIFEST_KIND = "virtual_mailbox"
LOCAL_PART_MAX_LENGTH = 64
+MAX_MAILBOX_QUOTA_MIB = 2**31 - 1
INVALID_LOCAL_PART = (
"Use 1 to 64 letters, digits, dots, underscores, or hyphens. "
"Start and end with a letter or digit and avoid consecutive dots."
@@ -20,6 +22,7 @@ INVALID_LOCAL_PART = (
class MailboxSpec:
domain: str
local_part: str
+ quota_mib: int | None = None
def __post_init__(self):
if not isinstance(self.domain, str):
@@ -44,36 +47,49 @@ class MailboxSpec:
raise ValueError(
"The full mailbox address must be at most 254 characters."
)
+ if self.quota_mib is not None and (
+ type(self.quota_mib) is not int
+ or not 1 <= self.quota_mib <= MAX_MAILBOX_QUOTA_MIB
+ ):
+ raise ValueError(
+ f"The mailbox storage limit must be between 1 and "
+ f"{MAX_MAILBOX_QUOTA_MIB} MiB."
+ )
@property
def address(self):
return f"{self.local_part}@{self.domain}"
def manifest(self):
- return {
+ result = {
"version": MANIFEST_VERSION,
"kind": MANIFEST_KIND,
"domain": self.domain,
"local_part": self.local_part,
}
+ if self.quota_mib is not None:
+ result["version"] = QUOTA_MANIFEST_VERSION
+ result["quota_mib"] = self.quota_mib
+ return result
@classmethod
def from_manifest(cls, data):
- if not isinstance(data, dict) or data.keys() != {
- "version",
- "kind",
- "domain",
- "local_part",
- }:
+ if not isinstance(data, dict) or data.get("kind") != MANIFEST_KIND:
raise ValueError("Expected a virtual mailbox manifest.")
- if (
- type(data["version"]) is not int
- or data["version"] != MANIFEST_VERSION
+ version = data.get("version")
+ if type(version) is not int or version not in (
+ MANIFEST_VERSION,
+ QUOTA_MANIFEST_VERSION,
):
raise ValueError("Unsupported mailbox manifest version.")
- if data["kind"] != MANIFEST_KIND:
+ fields = {"version", "kind", "domain", "local_part"}
+ if version == QUOTA_MANIFEST_VERSION:
+ fields.add("quota_mib")
+ if data.keys() != fields or (
+ version == QUOTA_MANIFEST_VERSION and data["quota_mib"] is None
+ ):
raise ValueError("Expected a virtual mailbox manifest.")
- return cls(data["domain"], data["local_part"])
+ return cls(data["domain"], data["local_part"], data.get("quota_mib"))
def main(argv=None):
@@ -138,7 +154,10 @@ def main(argv=None):
print(json.dumps(restore_mailbox(mailbox, args.archive), indent=2))
else:
- print(json.dumps({"address": mailbox.address}, indent=2))
+ report = {"address": mailbox.address}
+ if mailbox.quota_mib is not None:
+ report["quota_mib"] = mailbox.quota_mib
+ print(json.dumps(report, indent=2))
except (OSError, ValueError) as error:
parser.exit(1, f"coulobre-mail-node: {error}\n")
return 0
diff --git a/src/coulobre/mail_node_apply.py b/src/coulobre/mail_node_apply.py
index 78b4cd1..539201b 100644
--- a/src/coulobre/mail_node_apply.py
+++ b/src/coulobre/mail_node_apply.py
@@ -141,7 +141,7 @@ def mailbox_status(mailbox):
def configured_mail_account(mailbox):
for directory in (POSTFIX_DOMAINS.parent, DOVECOT_USERS.parent):
require_root_directory(directory)
- account, auth_group = check_services(mailbox)
+ account, auth_group, modern = check_services(mailbox)
path = credential_path(mailbox)
home = mailbox_home(mailbox)
if not os.path.lexists(path):
@@ -157,13 +157,16 @@ def configured_mail_account(mailbox):
return None
record = load_credentials(path)
+ check_registered_manifest(record, mailbox)
if not home_is_prepared(record):
raise ValueError("The mailbox installation is incomplete.")
+ if mailbox.quota_mib is not None:
+ check_dovecot_quota(modern)
for directory in (MAIL_ROOT, home.parent):
ensure_mail_directory(directory, create=False)
ensure_mail_home(home, account, create=False)
for table, (mode, group, rows) in lookup_tables(
- (record,), account, auth_group
+ (record,), account, auth_group, modern=modern
).items():
contents = read_lookup_table(table, mode, group)
if not contents.startswith(MANAGED_HEADER) or not rows.issubset(
@@ -181,6 +184,8 @@ def configured_mail_account(mailbox):
)
if dovecot_home(mailbox) != str(home):
raise ValueError("Dovecot did not resolve the managed mailbox home.")
+ if not dovecot_quota_matches(mailbox, modern):
+ raise ValueError("Dovecot did not resolve the mailbox storage limit.")
try:
run(
"doveadm",
@@ -199,18 +204,38 @@ def configured_mail_account(mailbox):
def install_mailbox(mailbox, state_directory):
- account, auth_group = check_services(mailbox)
+ account, auth_group, modern = check_services(mailbox)
records = [
load_credentials(path)
for path in sorted(STATE_DIRECTORY.glob("*.json"))
]
active = next(
- (record for record in records if record.mailbox == mailbox), None
+ (
+ record
+ for record in records
+ if record.path == credential_path(mailbox)
+ ),
+ None,
)
+ if active is not None:
+ check_registered_manifest(active, mailbox)
prepared = [record for record in records if home_is_prepared(record)]
- previous = lookup_tables(prepared, account, auth_group)
+ if mailbox.quota_mib is not None or any(
+ record.mailbox.quota_mib is not None for record in prepared
+ ):
+ check_dovecot_quota(modern)
+ previous = lookup_tables(prepared, account, auth_group, modern=modern)
+ old_dovecot_rows = (
+ dovecot_lookup_rows(prepared, account, modern=False)
+ if modern
+ else None
+ )
ready = {
- path: check_lookup_table(path, table)
+ path: check_lookup_table(
+ path,
+ table,
+ previous_rows=old_dovecot_rows if path == DOVECOT_USERS else None,
+ )
for path, table in previous.items()
}
home = mailbox_home(mailbox)
@@ -243,25 +268,28 @@ def install_mailbox(mailbox, state_directory):
else:
ensure_mail_home(home, account, create=False)
- tables = lookup_tables(prepared, account, auth_group)
+ tables = lookup_tables(prepared, account, auth_group, modern=modern)
publish_table(DOVECOT_USERS, tables[DOVECOT_USERS], ready[DOVECOT_USERS])
- wait_for_dovecot_home(mailbox, home)
+ wait_for_dovecot_user(mailbox, home, modern)
for path in (POSTFIX_MAILBOXES, POSTFIX_DOMAINS):
publish_table(path, tables[path], ready[path])
run("postfix", "reload")
return active.path
-def lookup_tables(records, account, auth_group):
+def check_registered_manifest(record, mailbox):
+ if record.mailbox != mailbox:
+ raise ValueError(
+ "The mailbox manifest differs from its registered storage limit."
+ )
+
+
+def lookup_tables(records, account, auth_group, *, modern):
return {
DOVECOT_USERS: (
0o640,
auth_group,
- {
- f"{record.mailbox.address}:{record.password_hash}:"
- f"{account.pw_uid}:{account.pw_gid}::{record.home}::"
- for record in records
- },
+ dovecot_lookup_rows(records, account, modern=modern),
),
POSTFIX_MAILBOXES: (
0o644,
@@ -276,6 +304,27 @@ def lookup_tables(records, account, auth_group):
}
+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
+
+
+def quota_userdb_setting(mailbox, modern):
+ size = f"{mailbox.quota_mib}M"
+ if modern:
+ return "quota_storage_size", size
+ return "quota_rule", f"*:bytes={size}"
+
+
def read_lookup_table(path, mode, group):
if not os.path.lexists(path):
return ""
@@ -287,12 +336,16 @@ def read_lookup_table(path, mode, group):
return contents
-def check_lookup_table(path, table):
+def check_lookup_table(path, table, *, previous_rows=None):
mode, group, rows = table
contents = read_lookup_table(path, mode, group)
+ observed = set(contents.removeprefix(MANAGED_HEADER).splitlines())
if contents and (
not contents.startswith(MANAGED_HEADER)
- or set(contents.removeprefix(MANAGED_HEADER).splitlines()) - rows
+ or (
+ observed - rows
+ and (previous_rows is None or observed - previous_rows)
+ )
):
raise ValueError(
f"Existing entries in {path} differ from Coulobre's registry."
@@ -384,7 +437,7 @@ def check_services(mailbox):
raise ValueError(
"The requested mail domain is a local Postfix destination."
)
- check_dovecot_maildir()
+ modern = check_dovecot_maildir()
first_uid = int(run("doveconf", "-h", "first_valid_uid"))
last_uid = int(run("doveconf", "-h", "last_valid_uid"))
if account.pw_uid < first_uid or (last_uid and account.pw_uid > last_uid):
@@ -402,12 +455,16 @@ def check_services(mailbox):
raise ValueError("The Dovecot auth group is missing.") from None
if not auth_group:
raise ValueError("The Dovecot auth group must be unprivileged.")
- return account, auth_group
+ return account, auth_group, modern
def check_dovecot_maildir():
version = re.match(r"(\d+)\.(\d+)", run("dovecot", "--version"))
- if version and tuple(map(int, version.groups())) >= (2, 4):
+ modern = version is not None and tuple(map(int, version.groups())) >= (
+ 2,
+ 4,
+ )
+ if modern:
if (
run("doveconf", "-h", "mail_driver") != "maildir"
or run("doveconf", "-h", "mail_path") != "~/Maildir"
@@ -420,6 +477,42 @@ def check_dovecot_maildir():
raise ValueError(
"Configure Dovecot mail_location for the managed Maildir."
)
+ return modern
+
+
+def check_dovecot_quota(modern):
+ problem = "Enable Dovecot quota enforcement for IMAP and LMTP."
+ global_quota = False
+ if modern:
+ if not re.search(
+ r"^quota .+ \{$", run("doveconf", "-n"), re.MULTILINE
+ ):
+ raise ValueError(
+ "Configure a Dovecot quota root for mailbox storage limits."
+ )
+ global_quota = (
+ "quota = yes" in run("doveconf", "-h", "mail_plugins").splitlines()
+ )
+ for protocol in ("imap", "lmtp"):
+ config = ("doveconf", "-f", f"protocol={protocol}", "-h")
+ plugins = run(*config, "mail_plugins")
+ if modern:
+ entries = plugins.splitlines()
+ # The protocol query omits inherited named-list entries.
+ enabled = "quota = yes" in entries or (
+ global_quota and "quota = no" not in entries
+ )
+ if not enabled or run(*config, "quota_enforce") != "yes":
+ raise ValueError(problem)
+ else:
+ driver, _, options = run(*config, "plugin/quota").partition(":")
+ if (
+ "quota" not in plugins.split()
+ or driver != "count"
+ or "noenforcing" in options.split(":")
+ or run(*config, "plugin/quota_vsizes") != "yes"
+ ):
+ raise ValueError(problem)
def dovecot_home(mailbox):
@@ -439,15 +532,25 @@ def postfix_lookup(key, path):
)
-def wait_for_dovecot_home(mailbox, home):
+def dovecot_quota_matches(mailbox, modern):
+ if mailbox.quota_mib is None:
+ 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):
# Dovecot checks for passwd-file changes at most once per second.
for _ in range(10):
resolved = dovecot_home(mailbox)
if resolved == str(home):
- return
- if resolved is not None:
+ if dovecot_quota_matches(mailbox, modern):
+ return
+ elif resolved is not None:
break
time.sleep(0.2)
+ if resolved == str(home):
+ raise ValueError("Dovecot did not resolve the mailbox storage limit.")
raise ValueError("Dovecot did not resolve the managed mailbox home.")
diff --git a/src/coulobre/mail_node_backup.py b/src/coulobre/mail_node_backup.py
index 7bd7061..3800461 100644
--- a/src/coulobre/mail_node_backup.py
+++ b/src/coulobre/mail_node_backup.py
@@ -228,5 +228,8 @@ def validate_metadata(archive, member, mailbox):
or metadata["kind"] != BACKUP_KIND
):
raise ValueError("Expected a supported native mailbox backup.")
- if MailboxSpec.from_manifest(metadata["mailbox"]) != mailbox:
+ if (
+ MailboxSpec.from_manifest(metadata["mailbox"]).address
+ != mailbox.address
+ ):
raise ValueError("The backup is for a different mailbox.")