Allow trusted mail receivers to assign unused domains to scoped panels
This commit is contained in:
1 parent
d1a221e01b
commit
0a04c85f7c
5 files changed
+328
-1
No files matched your search
@@ -0,0 +1,115 @@
|
|||||||
|
import json
|
||||||
|
import os
|
||||||
|
from dataclasses import dataclass
|
||||||
|
|
||||||
|
from .domain_names import canonical_domain
|
||||||
|
from .node_files import read_root_file, replace_configuration
|
||||||
|
|
||||||
|
OPERATION = "assign_mail_domain"
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True)
|
||||||
|
class MailDomainAssignment:
|
||||||
|
domain: str
|
||||||
|
|
||||||
|
def __post_init__(self):
|
||||||
|
if not isinstance(self.domain, str):
|
||||||
|
raise ValueError("Enter a valid domain name.")
|
||||||
|
object.__setattr__(self, "domain", canonical_domain(self.domain))
|
||||||
|
|
||||||
|
def manifest(self):
|
||||||
|
return {"version": 1, "operation": OPERATION, "domain": self.domain}
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def from_manifest(cls, data):
|
||||||
|
if (
|
||||||
|
not isinstance(data, dict)
|
||||||
|
or data.keys() != {"version", "operation", "domain"}
|
||||||
|
or data["operation"] != OPERATION
|
||||||
|
or type(data["version"]) is not int
|
||||||
|
or data["version"] != 1
|
||||||
|
):
|
||||||
|
raise ValueError("Expected a mail domain assignment request.")
|
||||||
|
return cls(data["domain"])
|
||||||
|
|
||||||
|
|
||||||
|
def assign_scoped_mail_domain(peer, domain):
|
||||||
|
"""Reserve one mail domain while the receiver scope lock is held."""
|
||||||
|
from .receiver_scope import (
|
||||||
|
mail_domain_assignment_path,
|
||||||
|
scope_files,
|
||||||
|
scope_path,
|
||||||
|
scoped_domains,
|
||||||
|
)
|
||||||
|
|
||||||
|
path = scope_path(peer)
|
||||||
|
domains = scoped_domains(path)
|
||||||
|
if domain in domains:
|
||||||
|
return
|
||||||
|
if any(
|
||||||
|
domain in scoped_domains(other)
|
||||||
|
for other in scope_files("mail")
|
||||||
|
if other != path
|
||||||
|
):
|
||||||
|
raise ValueError(
|
||||||
|
"The linked mail node already assigned this domain to another "
|
||||||
|
"panel. Ask the mail node administrator to review the assignment."
|
||||||
|
)
|
||||||
|
try:
|
||||||
|
allowed = read_root_file(mail_domain_assignment_path(peer), mode=0o600)
|
||||||
|
except FileNotFoundError:
|
||||||
|
allowed = ""
|
||||||
|
if allowed != "enabled\n":
|
||||||
|
raise ValueError(
|
||||||
|
"Ask the linked mail node administrator to assign this domain "
|
||||||
|
"to this panel or enable automatic mail domain assignment."
|
||||||
|
)
|
||||||
|
check_unused_mail_domain(domain)
|
||||||
|
replace_configuration(
|
||||||
|
path, json.dumps(sorted(domains | {domain})) + "\n", mode=0o600
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def check_unused_mail_domain(domain):
|
||||||
|
from . import mail_node_apply as mail
|
||||||
|
from .mail_node_dkim import KEY_DIRECTORY, MANAGED_DKIM_SELECTOR
|
||||||
|
from .mail_node_routing import (
|
||||||
|
POSTFIX_ALIASES,
|
||||||
|
check_alias_domain_configuration,
|
||||||
|
domain_aliases,
|
||||||
|
policy_directory,
|
||||||
|
)
|
||||||
|
from .mail_node_smtp_application import read_registry
|
||||||
|
|
||||||
|
# Do not assume a custom Postfix table excludes this domain.
|
||||||
|
check_alias_domain_configuration(domain)
|
||||||
|
for setting, table in (
|
||||||
|
("virtual_mailbox_domains", mail.POSTFIX_DOMAINS),
|
||||||
|
("virtual_mailbox_maps", mail.POSTFIX_MAILBOXES),
|
||||||
|
):
|
||||||
|
if mail.run("postconf", "-hx", setting) != f"proxy:texthash:{table}":
|
||||||
|
raise ValueError(
|
||||||
|
"The linked mail node has custom Postfix maps. Ask its "
|
||||||
|
"administrator to assign this domain manually."
|
||||||
|
)
|
||||||
|
with mail.locked_state(create=False, exclusive=True):
|
||||||
|
aliases = domain_aliases()
|
||||||
|
apps = read_registry(
|
||||||
|
mail.STATE_DIRECTORY / "smtp-applications" / "registry.json"
|
||||||
|
)
|
||||||
|
if (
|
||||||
|
domain in aliases
|
||||||
|
or domain in aliases.values()
|
||||||
|
or mail.postfix_lookup(domain, mail.POSTFIX_DOMAINS) is not None
|
||||||
|
or mail.postfix_lookup(domain, POSTFIX_ALIASES) is not None
|
||||||
|
or os.path.lexists(mail.MAIL_ROOT / domain)
|
||||||
|
or os.path.lexists(policy_directory() / f"{domain}.json")
|
||||||
|
or os.path.lexists(
|
||||||
|
KEY_DIRECTORY / f"{domain}.{MANAGED_DKIM_SELECTOR}.key"
|
||||||
|
)
|
||||||
|
or any(app["scope"]["domain"] == domain for app in apps.values())
|
||||||
|
):
|
||||||
|
raise ValueError(
|
||||||
|
"This domain already has resources on the linked mail node. "
|
||||||
|
"Ask its administrator to assign it manually."
|
||||||
|
)
|
||||||
@@ -6,6 +6,8 @@ from dataclasses import dataclass
|
|||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
|
|
||||||
from .domain_names import canonical_domain
|
from .domain_names import canonical_domain
|
||||||
|
from .mail_domain_assignment import OPERATION as ASSIGN_DOMAIN_OPERATION
|
||||||
|
from .mail_domain_assignment import MailDomainAssignment
|
||||||
from .node_requests import serve_apply_request
|
from .node_requests import serve_apply_request
|
||||||
from .node_retirement import RetirementRequest, parse_retirement
|
from .node_retirement import RetirementRequest, parse_retirement
|
||||||
from .service_access import ServiceAccessRequest, parse_service_request
|
from .service_access import ServiceAccessRequest, parse_service_request
|
||||||
@@ -182,6 +184,11 @@ def parse_mailbox_request(data):
|
|||||||
SmtpApplicationRequest,
|
SmtpApplicationRequest,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
if (
|
||||||
|
isinstance(data, dict)
|
||||||
|
and data.get("operation") == ASSIGN_DOMAIN_OPERATION
|
||||||
|
):
|
||||||
|
return MailDomainAssignment.from_manifest(data)
|
||||||
if (
|
if (
|
||||||
isinstance(data, dict)
|
isinstance(data, dict)
|
||||||
and data.get("operation") == SMTP_APPLICATION_OPERATION
|
and data.get("operation") == SMTP_APPLICATION_OPERATION
|
||||||
@@ -273,6 +280,9 @@ def apply_mailbox_request(request):
|
|||||||
)
|
)
|
||||||
from .smtp_application import SmtpApplicationRequest
|
from .smtp_application import SmtpApplicationRequest
|
||||||
|
|
||||||
|
# Scope authorization already handles the assignment.
|
||||||
|
if isinstance(request, MailDomainAssignment):
|
||||||
|
return None
|
||||||
if isinstance(request, SmtpApplicationRequest):
|
if isinstance(request, SmtpApplicationRequest):
|
||||||
from .mail_node_smtp_application import apply_smtp_application
|
from .mail_node_smtp_application import apply_smtp_application
|
||||||
|
|
||||||
|
|||||||
@@ -32,6 +32,7 @@ from .node_maintenance import (
|
|||||||
)
|
)
|
||||||
from .node_probe import PROBE_BYTES, PROBE_LIMIT, check_receiver, verify_probe
|
from .node_probe import PROBE_BYTES, PROBE_LIMIT, check_receiver, verify_probe
|
||||||
from .receiver_scope import (
|
from .receiver_scope import (
|
||||||
|
mail_domain_assignment_path,
|
||||||
scope_files,
|
scope_files,
|
||||||
scope_path,
|
scope_path,
|
||||||
scoped_account,
|
scoped_account,
|
||||||
@@ -356,6 +357,22 @@ def has_authorized_key(line, key):
|
|||||||
return any(" ".join(tokens[start : start + 2]) == key for start in (0, 1))
|
return any(" ".join(tokens[start : start + 2]) == key for start in (0, 1))
|
||||||
|
|
||||||
|
|
||||||
|
def set_mail_domain_assignment(panel, enabled):
|
||||||
|
account = scoped_account("mail", panel)
|
||||||
|
with locked_root_directory(NODE_KEYS):
|
||||||
|
if rollout_target("mail"):
|
||||||
|
raise ValueError("The receiver is in upgrade maintenance.")
|
||||||
|
if not scope_path(account).exists():
|
||||||
|
raise ValueError("Authorize this scoped mail panel first.")
|
||||||
|
scoped_domains(scope_path(account))
|
||||||
|
check_ssh_receiver(ROLES["mail"], account)
|
||||||
|
path = mail_domain_assignment_path(account)
|
||||||
|
if enabled:
|
||||||
|
replace_configuration(path, "enabled\n", mode=0o600)
|
||||||
|
else:
|
||||||
|
path.unlink(missing_ok=True)
|
||||||
|
|
||||||
|
|
||||||
def prepare_panel(role):
|
def prepare_panel(role):
|
||||||
require_root_directory(PANEL_SSH, create_mode=0o755)
|
require_root_directory(PANEL_SSH, create_mode=0o755)
|
||||||
with locked_root_directory(PANEL_SSH):
|
with locked_root_directory(PANEL_SSH):
|
||||||
@@ -567,6 +584,12 @@ def main(argv=None):
|
|||||||
"install-receiver", help="Install local receiver units."
|
"install-receiver", help="Install local receiver units."
|
||||||
)
|
)
|
||||||
install.add_argument("roles", nargs="+", choices=ROLES)
|
install.add_argument("roles", nargs="+", choices=ROLES)
|
||||||
|
assignment = commands.add_parser(
|
||||||
|
"mail-domain-assignment",
|
||||||
|
help="Allow a trusted scoped mail panel to register unused domains.",
|
||||||
|
)
|
||||||
|
assignment.add_argument("panel")
|
||||||
|
assignment.add_argument("policy", choices=("enable", "disable"))
|
||||||
for command, help_text in (
|
for command, help_text in (
|
||||||
("prepare-panel", "Prepare and print the panel's public SSH key."),
|
("prepare-panel", "Prepare and print the panel's public SSH key."),
|
||||||
("authorize-panel", "Authorize a panel public key on this receiver."),
|
("authorize-panel", "Authorize a panel public key on this receiver."),
|
||||||
@@ -626,6 +649,10 @@ def main(argv=None):
|
|||||||
"services before enrolment."
|
"services before enrolment."
|
||||||
)
|
)
|
||||||
return 0
|
return 0
|
||||||
|
if args.command == "mail-domain-assignment":
|
||||||
|
set_mail_domain_assignment(args.panel, args.policy == "enable")
|
||||||
|
print(f"Automatic mail domain assignment: {args.policy}d.")
|
||||||
|
return 0
|
||||||
role = ROLES[args.role]
|
role = ROLES[args.role]
|
||||||
if args.command == "prepare-panel":
|
if args.command == "prepare-panel":
|
||||||
key, _ = prepare_panel(role)
|
key, _ = prepare_panel(role)
|
||||||
|
|||||||
@@ -9,6 +9,10 @@ import sys
|
|||||||
from contextlib import contextmanager
|
from contextlib import contextmanager
|
||||||
|
|
||||||
from .domain_names import canonical_domain
|
from .domain_names import canonical_domain
|
||||||
|
from .mail_domain_assignment import (
|
||||||
|
MailDomainAssignment,
|
||||||
|
assign_scoped_mail_domain,
|
||||||
|
)
|
||||||
from .node_files import (
|
from .node_files import (
|
||||||
locked_root_directory,
|
locked_root_directory,
|
||||||
read_root_file,
|
read_root_file,
|
||||||
@@ -43,6 +47,10 @@ def scope_path(account):
|
|||||||
return NODE_KEYS / f".scope-{account}.json"
|
return NODE_KEYS / f".scope-{account}.json"
|
||||||
|
|
||||||
|
|
||||||
|
def mail_domain_assignment_path(account):
|
||||||
|
return NODE_KEYS / f".domain-assignment-{account}"
|
||||||
|
|
||||||
|
|
||||||
def scoped_domains(path):
|
def scoped_domains(path):
|
||||||
require_root_directory(path.parent)
|
require_root_directory(path.parent)
|
||||||
domains = json.loads(read_root_file(path, mode=0o600))
|
domains = json.loads(read_root_file(path, mode=0o600))
|
||||||
@@ -91,13 +99,20 @@ def authorized_request(role, spec=None):
|
|||||||
if peer in (None, "root", LOCAL_WORKERS[role]):
|
if peer in (None, "root", LOCAL_WORKERS[role]):
|
||||||
yield
|
yield
|
||||||
return
|
return
|
||||||
with locked_root_directory(NODE_KEYS, shared=True):
|
assignment = role == "mail" and isinstance(spec, MailDomainAssignment)
|
||||||
|
with locked_root_directory(NODE_KEYS, shared=not assignment):
|
||||||
if peer == f"coulobre-{role}-request":
|
if peer == f"coulobre-{role}-request":
|
||||||
if scope_files(role):
|
if scope_files(role):
|
||||||
raise ValueError(
|
raise ValueError(
|
||||||
"Use a domain-scoped panel key for this receiver."
|
"Use a domain-scoped panel key for this receiver."
|
||||||
)
|
)
|
||||||
elif peer.startswith(f"coulobre-{role}-p-"):
|
elif peer.startswith(f"coulobre-{role}-p-"):
|
||||||
|
if assignment:
|
||||||
|
if rollout_target(role):
|
||||||
|
raise ValueError("The receiver is in upgrade maintenance.")
|
||||||
|
assign_scoped_mail_domain(peer, spec.domain)
|
||||||
|
yield
|
||||||
|
return
|
||||||
domains = scoped_domains(scope_path(peer))
|
domains = scoped_domains(scope_path(peer))
|
||||||
if spec is not None and manifest_domain(spec) not in domains:
|
if spec is not None and manifest_domain(spec) not in domains:
|
||||||
raise ValueError(
|
raise ValueError(
|
||||||
|
|||||||
@@ -0,0 +1,160 @@
|
|||||||
|
import json
|
||||||
|
from contextlib import nullcontext
|
||||||
|
from pathlib import Path
|
||||||
|
from tempfile import TemporaryDirectory
|
||||||
|
from unittest import TestCase
|
||||||
|
from unittest.mock import patch
|
||||||
|
|
||||||
|
from . import mail_node_apply, node_setup, receiver_scope
|
||||||
|
from .mail_domain_assignment import (
|
||||||
|
MailDomainAssignment,
|
||||||
|
check_unused_mail_domain,
|
||||||
|
)
|
||||||
|
from .mail_node import MailboxSpec, parse_mailbox_request
|
||||||
|
|
||||||
|
ALPHA = "coulobre-mail-p-alpha"
|
||||||
|
BETA = "coulobre-mail-p-beta"
|
||||||
|
DOMAIN = "new.example.test"
|
||||||
|
|
||||||
|
|
||||||
|
class MailDomainAssignmentTests(TestCase):
|
||||||
|
def setUp(self):
|
||||||
|
root = Path(self.enterContext(TemporaryDirectory()))
|
||||||
|
self.enterContext(patch.object(receiver_scope, "NODE_KEYS", root))
|
||||||
|
self.enterContext(patch.object(node_setup, "NODE_KEYS", root))
|
||||||
|
self.enterContext(
|
||||||
|
patch.object(receiver_scope, "require_root_directory")
|
||||||
|
)
|
||||||
|
self.peer = self.enterContext(
|
||||||
|
patch.object(receiver_scope, "socket_peer", return_value=ALPHA)
|
||||||
|
)
|
||||||
|
self.lock = self.enterContext(
|
||||||
|
patch.object(
|
||||||
|
receiver_scope,
|
||||||
|
"locked_root_directory",
|
||||||
|
return_value=nullcontext(),
|
||||||
|
)
|
||||||
|
)
|
||||||
|
self.maintenance = self.enterContext(
|
||||||
|
patch.object(receiver_scope, "rollout_target", return_value=None)
|
||||||
|
)
|
||||||
|
self.unused = self.enterContext(
|
||||||
|
patch("coulobre.mail_domain_assignment.check_unused_mail_domain")
|
||||||
|
)
|
||||||
|
self.enterContext(patch("coulobre.node_files.check_root_file"))
|
||||||
|
self.set_scope(ALPHA, ["existing.example.test"])
|
||||||
|
self.set_scope(BETA, ["other.example.test"])
|
||||||
|
self.assignment = MailDomainAssignment(DOMAIN)
|
||||||
|
|
||||||
|
def set_scope(self, account, domains):
|
||||||
|
receiver_scope.scope_path(account).write_text(json.dumps(domains))
|
||||||
|
|
||||||
|
def enable(self, account):
|
||||||
|
receiver_scope.mail_domain_assignment_path(account).write_text(
|
||||||
|
"enabled\n"
|
||||||
|
)
|
||||||
|
|
||||||
|
def request(self, spec):
|
||||||
|
with receiver_scope.authorized_request("mail", spec):
|
||||||
|
pass
|
||||||
|
|
||||||
|
def test_assignment_requires_explicit_opt_in_and_does_not_replace_scope(
|
||||||
|
self,
|
||||||
|
):
|
||||||
|
with self.assertRaisesRegex(ValueError, "administrator to assign"):
|
||||||
|
self.request(self.assignment)
|
||||||
|
self.unused.assert_not_called()
|
||||||
|
self.enable(ALPHA)
|
||||||
|
self.request(self.assignment)
|
||||||
|
self.lock.assert_called_with(receiver_scope.NODE_KEYS, shared=False)
|
||||||
|
self.request(self.assignment)
|
||||||
|
self.request(MailboxSpec(DOMAIN, "info"))
|
||||||
|
self.unused.assert_called_once_with(DOMAIN)
|
||||||
|
self.assertEqual(
|
||||||
|
receiver_scope.scoped_domains(receiver_scope.scope_path(ALPHA)),
|
||||||
|
{DOMAIN, "existing.example.test"},
|
||||||
|
)
|
||||||
|
self.assertEqual(
|
||||||
|
receiver_scope.scoped_domains(receiver_scope.scope_path(BETA)),
|
||||||
|
{"other.example.test"},
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_other_panel_cannot_claim_a_domain(self):
|
||||||
|
self.enable(ALPHA)
|
||||||
|
self.request(self.assignment)
|
||||||
|
self.peer.return_value = BETA
|
||||||
|
self.enable(BETA)
|
||||||
|
with self.assertRaisesRegex(ValueError, "assigned.*another panel"):
|
||||||
|
self.request(self.assignment)
|
||||||
|
with self.assertRaisesRegex(ValueError, "not assigned"):
|
||||||
|
self.request(MailboxSpec(DOMAIN, "info"))
|
||||||
|
self.unused.assert_called_once_with(DOMAIN)
|
||||||
|
|
||||||
|
def test_already_assigned_domain_needs_no_opt_in(self):
|
||||||
|
self.request(MailDomainAssignment("existing.example.test"))
|
||||||
|
self.unused.assert_not_called()
|
||||||
|
|
||||||
|
def test_no_claim_during_maintenance_or_via_legacy_key(self):
|
||||||
|
self.enable(ALPHA)
|
||||||
|
self.maintenance.return_value = "1.5.1"
|
||||||
|
with self.assertRaisesRegex(ValueError, "maintenance"):
|
||||||
|
self.request(self.assignment)
|
||||||
|
self.maintenance.return_value = None
|
||||||
|
self.peer.return_value = "coulobre-mail-request"
|
||||||
|
with self.assertRaisesRegex(ValueError, "domain-scoped"):
|
||||||
|
self.request(self.assignment)
|
||||||
|
self.unused.assert_not_called()
|
||||||
|
|
||||||
|
def test_registration_policy_preserves_the_scope(self):
|
||||||
|
with (
|
||||||
|
patch.object(node_setup, "rollout_target", return_value=None),
|
||||||
|
patch.object(node_setup, "check_ssh_receiver"),
|
||||||
|
patch.object(node_setup, "locked_root_directory", nullcontext),
|
||||||
|
):
|
||||||
|
node_setup.set_mail_domain_assignment("alpha", True)
|
||||||
|
self.request(self.assignment)
|
||||||
|
node_setup.set_mail_domain_assignment("alpha", False)
|
||||||
|
self.request(self.assignment)
|
||||||
|
with self.assertRaisesRegex(ValueError, "administrator to assign"):
|
||||||
|
self.request(MailDomainAssignment("another.example.test"))
|
||||||
|
|
||||||
|
def test_manifest_cannot_select_another_panel(self):
|
||||||
|
self.assertEqual(
|
||||||
|
parse_mailbox_request(self.assignment.manifest()), self.assignment
|
||||||
|
)
|
||||||
|
for extra in (
|
||||||
|
{"peer": BETA},
|
||||||
|
{"domain": None},
|
||||||
|
{"domain": "*.example.test"},
|
||||||
|
{"version": True},
|
||||||
|
):
|
||||||
|
with self.subTest(extra=extra), self.assertRaises(ValueError):
|
||||||
|
parse_mailbox_request(self.assignment.manifest() | extra)
|
||||||
|
|
||||||
|
def test_existing_receiver_resources_block_automatic_assignment(self):
|
||||||
|
with (
|
||||||
|
patch(
|
||||||
|
"coulobre.mail_node_routing.check_alias_domain_configuration"
|
||||||
|
),
|
||||||
|
patch(
|
||||||
|
"coulobre.mail_node_routing.domain_aliases", return_value={}
|
||||||
|
),
|
||||||
|
patch(
|
||||||
|
"coulobre.mail_node_smtp_application.read_registry",
|
||||||
|
return_value={},
|
||||||
|
),
|
||||||
|
patch.object(
|
||||||
|
mail_node_apply,
|
||||||
|
"run",
|
||||||
|
side_effect=[
|
||||||
|
f"proxy:texthash:{mail_node_apply.POSTFIX_DOMAINS}",
|
||||||
|
f"proxy:texthash:{mail_node_apply.POSTFIX_MAILBOXES}",
|
||||||
|
],
|
||||||
|
),
|
||||||
|
patch.object(
|
||||||
|
mail_node_apply, "locked_state", return_value=nullcontext()
|
||||||
|
),
|
||||||
|
patch.object(mail_node_apply, "postfix_lookup", return_value="1"),
|
||||||
|
self.assertRaisesRegex(ValueError, "already has resources"),
|
||||||
|
):
|
||||||
|
check_unused_mail_domain(DOMAIN)
|
||||||
Reference in new issue
Block a user