Enforce per-mailbox storage limits with Dovecot

This commit is contained in:
parkel committed 2026-11-21 13:02:06 +01:00
1 parent 056858db0d
commit 57a9a67bae
6 files changed
+263 -38

No files matched your search

+11
View File
@@ -8,6 +8,17 @@ ssl_server_key_file = /etc/ssl/coulobre-mail/privkey.pem
mail_driver = maildir mail_driver = maildir
mail_path = ~/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. # Set both values to the UID of coulobre-vmail.
first_valid_uid = 103 first_valid_uid = 103
last_valid_uid = 103 last_valid_uid = 103
+77 -2
View File
@@ -15,6 +15,7 @@ from coulobre.mail_node import MailboxSpec, main
from coulobre.mail_node_apply import ( from coulobre.mail_node_apply import (
apply_mailbox, apply_mailbox,
check_dovecot_maildir, check_dovecot_maildir,
check_dovecot_quota,
credential_path, credential_path,
ensure_mail_home, ensure_mail_home,
mailbox_status, mailbox_status,
@@ -97,10 +98,10 @@ class MailboxApplyTests(SimpleTestCase):
) )
) )
self.account = SimpleNamespace(pw_uid=1001, pw_gid=1001) self.account = SimpleNamespace(pw_uid=1001, pw_gid=1001)
self.enterContext( self.services = self.enterContext(
patch( patch(
"coulobre.mail_node_apply.check_services", "coulobre.mail_node_apply.check_services",
return_value=(self.account, os.getegid()), return_value=(self.account, os.getegid(), False),
) )
) )
self.resolve_home = self.enterContext( self.resolve_home = self.enterContext(
@@ -171,6 +172,52 @@ class MailboxApplyTests(SimpleTestCase):
self.assertEqual(credential_file.read_bytes(), original) self.assertEqual(credential_file.read_bytes(), original)
self.assertIn("support@example.net\t1", self.mailboxes.read_text()) 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): def test_waits_for_dovecot_to_read_the_updated_authentication_file(self):
home = self.storage / self.spec.domain / self.spec.local_part home = self.storage / self.spec.domain / self.spec.local_part
self.resolve_home.side_effect = [None, None, str(home)] self.resolve_home.side_effect = [None, None, str(home)]
@@ -323,6 +370,34 @@ class MailboxCommandTests(SimpleTestCase):
): ):
check_dovecot_maildir() 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): def test_dovecot_23_checks_the_legacy_maildir_setting(self):
with patch( with patch(
"coulobre.mail_node_apply.run", "coulobre.mail_node_apply.run",
@@ -106,6 +106,20 @@ class MailboxBackupTests(SimpleTestCase):
self.assertFalse((self.home / "Maildir").exists()) 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): def test_corrupt_backup_leaves_no_restored_maildir(self):
self.make_archive() self.make_archive()
self.archive.write_bytes(self.archive.read_bytes()[:-4]) self.archive.write_bytes(self.archive.read_bytes()[:-4])
+32 -13
View File
@@ -8,8 +8,10 @@ from .domain_names import canonical_domain
from .node_requests import serve_apply_request from .node_requests import serve_apply_request
MANIFEST_VERSION = 1 MANIFEST_VERSION = 1
QUOTA_MANIFEST_VERSION = 2
MANIFEST_KIND = "virtual_mailbox" MANIFEST_KIND = "virtual_mailbox"
LOCAL_PART_MAX_LENGTH = 64 LOCAL_PART_MAX_LENGTH = 64
MAX_MAILBOX_QUOTA_MIB = 2**31 - 1
INVALID_LOCAL_PART = ( INVALID_LOCAL_PART = (
"Use 1 to 64 letters, digits, dots, underscores, or hyphens. " "Use 1 to 64 letters, digits, dots, underscores, or hyphens. "
"Start and end with a letter or digit and avoid consecutive dots." "Start and end with a letter or digit and avoid consecutive dots."
@@ -20,6 +22,7 @@ INVALID_LOCAL_PART = (
class MailboxSpec: class MailboxSpec:
domain: str domain: str
local_part: str local_part: str
quota_mib: int | None = None
def __post_init__(self): def __post_init__(self):
if not isinstance(self.domain, str): if not isinstance(self.domain, str):
@@ -44,36 +47,49 @@ class MailboxSpec:
raise ValueError( raise ValueError(
"The full mailbox address must be at most 254 characters." "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 @property
def address(self): def address(self):
return f"{self.local_part}@{self.domain}" return f"{self.local_part}@{self.domain}"
def manifest(self): def manifest(self):
return { result = {
"version": MANIFEST_VERSION, "version": MANIFEST_VERSION,
"kind": MANIFEST_KIND, "kind": MANIFEST_KIND,
"domain": self.domain, "domain": self.domain,
"local_part": self.local_part, "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 @classmethod
def from_manifest(cls, data): def from_manifest(cls, data):
if not isinstance(data, dict) or data.keys() != { if not isinstance(data, dict) or data.get("kind") != MANIFEST_KIND:
"version",
"kind",
"domain",
"local_part",
}:
raise ValueError("Expected a virtual mailbox manifest.") raise ValueError("Expected a virtual mailbox manifest.")
if ( version = data.get("version")
type(data["version"]) is not int if type(version) is not int or version not in (
or data["version"] != MANIFEST_VERSION MANIFEST_VERSION,
QUOTA_MANIFEST_VERSION,
): ):
raise ValueError("Unsupported mailbox 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.") 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): def main(argv=None):
@@ -138,7 +154,10 @@ def main(argv=None):
print(json.dumps(restore_mailbox(mailbox, args.archive), indent=2)) print(json.dumps(restore_mailbox(mailbox, args.archive), indent=2))
else: 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: except (OSError, ValueError) as error:
parser.exit(1, f"coulobre-mail-node: {error}\n") parser.exit(1, f"coulobre-mail-node: {error}\n")
return 0 return 0
+125 -22
View File
@@ -141,7 +141,7 @@ def mailbox_status(mailbox):
def configured_mail_account(mailbox): def configured_mail_account(mailbox):
for directory in (POSTFIX_DOMAINS.parent, DOVECOT_USERS.parent): for directory in (POSTFIX_DOMAINS.parent, DOVECOT_USERS.parent):
require_root_directory(directory) require_root_directory(directory)
account, auth_group = check_services(mailbox) account, auth_group, modern = check_services(mailbox)
path = credential_path(mailbox) path = credential_path(mailbox)
home = mailbox_home(mailbox) home = mailbox_home(mailbox)
if not os.path.lexists(path): if not os.path.lexists(path):
@@ -157,13 +157,16 @@ def configured_mail_account(mailbox):
return None return None
record = load_credentials(path) record = load_credentials(path)
check_registered_manifest(record, mailbox)
if not home_is_prepared(record): if not home_is_prepared(record):
raise ValueError("The mailbox installation is incomplete.") 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): for directory in (MAIL_ROOT, home.parent):
ensure_mail_directory(directory, create=False) ensure_mail_directory(directory, create=False)
ensure_mail_home(home, account, create=False) ensure_mail_home(home, account, create=False)
for table, (mode, group, rows) in lookup_tables( for table, (mode, group, rows) in lookup_tables(
(record,), account, auth_group (record,), account, auth_group, modern=modern
).items(): ).items():
contents = read_lookup_table(table, mode, group) contents = read_lookup_table(table, mode, group)
if not contents.startswith(MANAGED_HEADER) or not rows.issubset( 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): if dovecot_home(mailbox) != str(home):
raise ValueError("Dovecot did not resolve the managed mailbox 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: try:
run( run(
"doveadm", "doveadm",
@@ -199,18 +204,38 @@ def configured_mail_account(mailbox):
def install_mailbox(mailbox, state_directory): def install_mailbox(mailbox, state_directory):
account, auth_group = check_services(mailbox) account, auth_group, modern = check_services(mailbox)
records = [ records = [
load_credentials(path) load_credentials(path)
for path in sorted(STATE_DIRECTORY.glob("*.json")) for path in sorted(STATE_DIRECTORY.glob("*.json"))
] ]
active = next( 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)] 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 = { 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() for path, table in previous.items()
} }
home = mailbox_home(mailbox) home = mailbox_home(mailbox)
@@ -243,25 +268,28 @@ def install_mailbox(mailbox, state_directory):
else: else:
ensure_mail_home(home, account, create=False) 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]) 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): for path in (POSTFIX_MAILBOXES, POSTFIX_DOMAINS):
publish_table(path, tables[path], ready[path]) publish_table(path, tables[path], ready[path])
run("postfix", "reload") run("postfix", "reload")
return active.path 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 { return {
DOVECOT_USERS: ( DOVECOT_USERS: (
0o640, 0o640,
auth_group, auth_group,
{ dovecot_lookup_rows(records, account, modern=modern),
f"{record.mailbox.address}:{record.password_hash}:"
f"{account.pw_uid}:{account.pw_gid}::{record.home}::"
for record in records
},
), ),
POSTFIX_MAILBOXES: ( POSTFIX_MAILBOXES: (
0o644, 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): def read_lookup_table(path, mode, group):
if not os.path.lexists(path): if not os.path.lexists(path):
return "" return ""
@@ -287,12 +336,16 @@ def read_lookup_table(path, mode, group):
return contents return contents
def check_lookup_table(path, table): def check_lookup_table(path, table, *, previous_rows=None):
mode, group, rows = table mode, group, rows = table
contents = read_lookup_table(path, mode, group) contents = read_lookup_table(path, mode, group)
observed = set(contents.removeprefix(MANAGED_HEADER).splitlines())
if contents and ( if contents and (
not contents.startswith(MANAGED_HEADER) 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( raise ValueError(
f"Existing entries in {path} differ from Coulobre's registry." f"Existing entries in {path} differ from Coulobre's registry."
@@ -384,7 +437,7 @@ def check_services(mailbox):
raise ValueError( raise ValueError(
"The requested mail domain is a local Postfix destination." "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")) first_uid = int(run("doveconf", "-h", "first_valid_uid"))
last_uid = int(run("doveconf", "-h", "last_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): 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 raise ValueError("The Dovecot auth group is missing.") from None
if not auth_group: if not auth_group:
raise ValueError("The Dovecot auth group must be unprivileged.") raise ValueError("The Dovecot auth group must be unprivileged.")
return account, auth_group return account, auth_group, modern
def check_dovecot_maildir(): def check_dovecot_maildir():
version = re.match(r"(\d+)\.(\d+)", run("dovecot", "--version")) 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 ( if (
run("doveconf", "-h", "mail_driver") != "maildir" run("doveconf", "-h", "mail_driver") != "maildir"
or run("doveconf", "-h", "mail_path") != "~/Maildir" or run("doveconf", "-h", "mail_path") != "~/Maildir"
@@ -420,6 +477,42 @@ def check_dovecot_maildir():
raise ValueError( raise ValueError(
"Configure Dovecot mail_location for the managed Maildir." "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): 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. # Dovecot checks for passwd-file changes at most once per second.
for _ in range(10): for _ in range(10):
resolved = dovecot_home(mailbox) resolved = dovecot_home(mailbox)
if resolved == str(home): if resolved == str(home):
return if dovecot_quota_matches(mailbox, modern):
if resolved is not None: return
elif resolved is not None:
break break
time.sleep(0.2) 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.") raise ValueError("Dovecot did not resolve the managed mailbox home.")
+4 -1
View File
@@ -228,5 +228,8 @@ def validate_metadata(archive, member, mailbox):
or metadata["kind"] != BACKUP_KIND or metadata["kind"] != BACKUP_KIND
): ):
raise ValueError("Expected a supported native mailbox backup.") 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.") raise ValueError("The backup is for a different mailbox.")