From c2655b57f57f834fb9274d9bc8bd57b213bc0553 Mon Sep 17 00:00:00 2001 From: Peter van Arkel Date: Sat, 21 Nov 2026 19:23:01 +0100 Subject: [PATCH 1/3] Rotate managed database and mailbox passwords on their nodes --- src/coulobre/credential_rotation.py | 95 ++++++++++++++ src/coulobre/database_node_apply.py | 26 +++- src/coulobre/database_node_rotation.py | 81 ++++++++++++ src/coulobre/hosting/test_mail_node_apply.py | 46 +++++++ .../hosting/test_service_credentials.py | 2 +- src/coulobre/mail_node_apply.py | 88 ++++++++++--- src/coulobre/mail_node_quota.py | 3 + src/coulobre/mail_node_rotation.py | 60 +++++++++ src/coulobre/service_credentials.py | 121 +++++++++++++++--- 9 files changed, 480 insertions(+), 42 deletions(-) create mode 100644 src/coulobre/credential_rotation.py create mode 100644 src/coulobre/database_node_rotation.py create mode 100644 src/coulobre/mail_node_rotation.py diff --git a/src/coulobre/credential_rotation.py b/src/coulobre/credential_rotation.py new file mode 100644 index 0000000..1ea4436 --- /dev/null +++ b/src/coulobre/credential_rotation.py @@ -0,0 +1,95 @@ +import json +import os +import re +import secrets +from pathlib import Path +from tempfile import TemporaryDirectory +from uuid import UUID + +from .node_files import read_root_file, write_new_file + +PASSWORD = re.compile(r"[A-Za-z0-9_-]{43}") +ROTATION_IN_PROGRESS = ( + "Retry the current credential change before starting another." +) + + +def valid_generation(value): + if value is None: + return True + if not isinstance(value, str): + return False + try: + return str(UUID(value)) == value + except ValueError: + return False + + +def rotation_path(path): + return path.with_suffix(".rotation") + + +def load_pending_rotation(path): + try: + pending = json.loads(read_root_file(rotation_path(path), mode=0o600)) + except FileNotFoundError: + return None + if ( + not isinstance(pending, dict) + or not isinstance(pending.get("id"), str) + or not valid_generation(pending["id"]) + or "previous" not in pending + or not valid_generation(pending["previous"]) + or not isinstance(pending.get("password"), str) + or not PASSWORD.fullmatch(pending["password"]) + ): + raise ValueError("The pending credential record is invalid.") + return pending + + +def stage_rotation(path, request, generation, *, hash_password=None): + pending = load_pending_rotation(path) + if pending is not None and ( + pending["id"] != request.rotation_id + or pending["previous"] != request.previous_id + ): + raise ValueError(ROTATION_IN_PROGRESS) + if generation not in (request.previous_id, request.rotation_id): + raise ValueError( + "The credential changed after this request was opened." + ) + if pending is not None or generation == request.rotation_id: + return pending + + password = secrets.token_urlsafe(32) + pending = { + "id": request.rotation_id, + "previous": generation, + "password": password, + } + if hash_password is not None: + pending["password_hash"] = hash_password(password) + write_new_file(rotation_path(path), json.dumps(pending), mode=0o600) + sync_directory(path.parent) + return pending + + +def save_credential_record(path, record): + with TemporaryDirectory(dir=path.parent) as scratch: + staged = Path(scratch) / "credentials" + write_new_file(staged, json.dumps(record, indent=2) + "\n", mode=0o600) + os.replace(staged, path) + sync_directory(path.parent) + + +def finish_rotation(path): + rotation_path(path).unlink(missing_ok=True) + sync_directory(path.parent) + + +def sync_directory(path): + directory = os.open(path, os.O_RDONLY | os.O_DIRECTORY) + try: + os.fsync(directory) + finally: + os.close(directory) diff --git a/src/coulobre/database_node_apply.py b/src/coulobre/database_node_apply.py index 87634a0..5c29418 100644 --- a/src/coulobre/database_node_apply.py +++ b/src/coulobre/database_node_apply.py @@ -5,6 +5,11 @@ import secrets from contextlib import closing, contextmanager, suppress from pathlib import Path +from .credential_rotation import ( + ROTATION_IN_PROGRESS, + rotation_path, + valid_generation, +) from .node_files import read_root_file, require_root_directory, write_new_file STATE_DIRECTORY = Path("/var/lib/coulobre/database-node") @@ -117,6 +122,7 @@ def checked_credentials( *, restoring=False, verify_login=True, + pending_password=None, ): name = database.name schema, users = read_resources(cursor, name) @@ -136,7 +142,20 @@ def checked_credentials( raise ValueError("The database installation is incomplete.") if not restoring: check_restore_complete(record_path) - password_hash = native_password_hash(record["password"]) + if pending_password is None and os.path.lexists( + rotation_path(record_path) + ): + raise ValueError(ROTATION_IN_PROGRESS) + password = record["password"] + if pending_password is not None and users == ( + ( + "localhost", + "mysql_native_password", + native_password_hash(pending_password), + ), + ): + password = pending_password + password_hash = native_password_hash(password) check_resources( schema, users, @@ -169,7 +188,7 @@ def checked_credentials( driver.connect( host="localhost", user=name, - passwd=record["password"], + passwd=password, db=name, unix_socket=str(socket), connect_timeout=5, @@ -193,6 +212,8 @@ def check_restore_complete(record_path): def install_database(cursor, database, socket, record_path): + if os.path.lexists(rotation_path(record_path)): + raise ValueError(ROTATION_IN_PROGRESS) check_restore_complete(record_path) name = database.name schema, users = read_resources(cursor, name) @@ -270,6 +291,7 @@ def load_credentials(database, socket, path): or not isinstance(record.get("password"), str) or not record["password"] or not record["password"].isascii() + or not valid_generation(record.get("rotation_id")) or not isinstance(record.get("ownership"), str) or not record["ownership"] ): diff --git a/src/coulobre/database_node_rotation.py b/src/coulobre/database_node_rotation.py new file mode 100644 index 0000000..1ebae22 --- /dev/null +++ b/src/coulobre/database_node_rotation.py @@ -0,0 +1,81 @@ +from contextlib import closing + +from . import database_node_apply as db +from .credential_rotation import ( + finish_rotation, + load_pending_rotation, + save_credential_record, + stage_rotation, +) + +ACCESS_DENIED = 1045 + + +def rotate_database_credentials(request, socket): + database = request.resource + socket = socket.resolve() + path = db.STATE_DIRECTORY / f"{database.name}.json" + with db.locked_cursor(database, socket) as (driver, cursor): + pending = load_pending_rotation(path) + record = db.checked_credentials( + driver, + cursor, + database, + socket, + path, + pending_password=pending["password"] if pending else None, + ) + if record is None: + raise ValueError( + "Apply the database manifest before rotating its login." + ) + if db.login_is_locked(cursor, database.name): + raise ValueError( + "Resume the database login before rotating its password." + ) + generation = record.get("rotation_id") + pending = stage_rotation(path, request, generation) + if generation != request.rotation_id: + password = pending["password"] + cursor.execute( + "ALTER USER %s@'localhost' " + "IDENTIFIED VIA mysql_native_password USING %s", + (database.name, db.native_password_hash(password)), + ) + db.checked_credentials( + driver, + cursor, + database, + socket, + path, + pending_password=password, + ) + verify_old_password_rejected(driver, record) + record = record | { + "password": password, + "rotation_id": request.rotation_id, + } + save_credential_record(path, record) + finish_rotation(path) + return record + + +def verify_old_password_rejected(driver, record): + try: + with closing( + driver.connect( + host="localhost", + user=record["user"], + passwd=record["password"], + db=record["database"], + unix_socket=record["socket"], + connect_timeout=5, + charset="utf8mb4", + ) + ): + pass + except driver.Error as error: + if error.args and error.args[0] == ACCESS_DENIED: + return + raise + raise ValueError("MariaDB still accepts the previous password.") diff --git a/src/coulobre/hosting/test_mail_node_apply.py b/src/coulobre/hosting/test_mail_node_apply.py index 8f3579d..89df456 100644 --- a/src/coulobre/hosting/test_mail_node_apply.py +++ b/src/coulobre/hosting/test_mail_node_apply.py @@ -8,6 +8,7 @@ from subprocess import CompletedProcess from tempfile import TemporaryDirectory from types import SimpleNamespace from unittest.mock import patch +from uuid import uuid4 from django.test import SimpleTestCase @@ -18,10 +19,13 @@ from coulobre.mail_node_apply import ( check_dovecot_quota, credential_path, ensure_mail_home, + load_credentials, mailbox_status, run, ) from coulobre.mail_node_quota import set_mailbox_access, set_mailbox_quota +from coulobre.mail_node_rotation import rotate_mailbox_credentials +from coulobre.service_credentials import ServiceCredentialRequest class MailboxApplyRequestTests(SimpleTestCase): @@ -301,6 +305,48 @@ class MailboxApplyTests(SimpleTestCase): self.assertEqual(self.users.read_bytes(), table) self.assertEqual(path.read_bytes(), credentials) + def test_interrupted_rotation_does_not_block_another_mailbox(self): + path = apply_mailbox(self.spec) + original = load_credentials(path) + replacement_hash = "{SHA512-CRYPT}$6$mockSalt$" + ("B" * 86) + rotation = ServiceCredentialRequest(self.spec, "rotate", str(uuid4())) + self.postfix_lookup.return_value = "1" + with ( + patch("coulobre.mail_node_quota.require_root_directory"), + patch("coulobre.mail_node_apply.wait_for_dovecot_user"), + patch( + "coulobre.mail_node_rotation.verify_mailbox_rotation" + ) as verify, + patch( + "coulobre.credential_rotation.read_root_file", + side_effect=lambda path, **kwargs: path.read_text(), + ), + ): + verify.side_effect = OSError("Verification interrupted.") + with ( + patch( + "coulobre.mail_node_apply.hash_mailbox_password", + return_value=replacement_hash, + ), + self.assertRaisesMessage(OSError, "Verification interrupted"), + ): + rotate_mailbox_credentials(rotation) + self.assertEqual(load_credentials(path), original) + self.assertIn(replacement_hash, self.users.read_text()) + + sibling = MailboxSpec("other.example", "support") + apply_mailbox(sibling) + self.assertIn(replacement_hash, self.users.read_text()) + self.assertIn(sibling.address, self.mailboxes.read_text()) + + verify.side_effect = None + result = rotate_mailbox_credentials(rotation) + self.assertNotEqual(result["password"], original.password) + self.assertEqual( + load_credentials(path).rotation_id, rotation.rotation_id + ) + self.assertEqual(rotate_mailbox_credentials(rotation), result) + 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_service_credentials.py b/src/coulobre/hosting/test_service_credentials.py index d7270a8..008d39b 100644 --- a/src/coulobre/hosting/test_service_credentials.py +++ b/src/coulobre/hosting/test_service_credentials.py @@ -328,7 +328,7 @@ class NativeServiceCredentialTests(SimpleTestCase): patch("sys.stdin", SimpleNamespace(buffer=source)), redirect_stdout(StringIO()) as output, ): - result = service_credentials.main() + result = service_credentials.main([]) return result, json.loads(output.getvalue()) def test_the_database_socket_accepts_only_managed_resource_identity(self): diff --git a/src/coulobre/mail_node_apply.py b/src/coulobre/mail_node_apply.py index fe62fcd..78a75f0 100644 --- a/src/coulobre/mail_node_apply.py +++ b/src/coulobre/mail_node_apply.py @@ -10,10 +10,18 @@ import stat import subprocess import time from contextlib import contextmanager -from dataclasses import dataclass +from dataclasses import dataclass, replace from pathlib import Path from tempfile import TemporaryDirectory +from .credential_rotation import ( + PASSWORD, + ROTATION_IN_PROGRESS, + load_pending_rotation, + rotation_path, + save_credential_record, + valid_generation, +) from .mail_node import MailboxSpec from .node_files import read_root_file, require_root_directory, write_new_file @@ -25,7 +33,6 @@ POSTFIX_MAILBOXES = Path("/etc/postfix/coulobre-mailboxes") DOVECOT_USERS = Path("/etc/dovecot/coulobre-users") LMTP_SOCKET = Path("/var/spool/postfix/private/dovecot-lmtp") MANAGED_HEADER = "# Managed by Coulobre Panel\n" -PASSWORD = re.compile(r"[A-Za-z0-9_-]{43}") PASSWORD_HASH = re.compile( r"\{SHA512-CRYPT\}\$6\$(?:rounds=[0-9]+\$)?" r"[./0-9A-Za-z]{1,16}\$[./0-9A-Za-z]{86}" @@ -38,6 +45,7 @@ class Credentials: password: str password_hash: str suspended: bool = False + rotation_id: str | None = None @property def home(self): @@ -59,14 +67,14 @@ class Credentials: } if self.suspended: document["suspended"] = True - text = json.dumps(document, indent=2) + "\n" + if self.rotation_id is not None: + document["rotation_id"] = self.rotation_id 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) + save_credential_record(self.path, document) else: - write_new_file(self.path, text, mode=0o600) + write_new_file( + self.path, json.dumps(document, indent=2) + "\n", mode=0o600 + ) def credential_path(mailbox): @@ -86,10 +94,12 @@ def load_credentials(path): data["password"], data["password_hash"], data.get("suspended", False), + data.get("rotation_id"), ) if ( record.path != path or type(record.suspended) is not bool + or not valid_generation(record.rotation_id) or not PASSWORD.fullmatch(record.password) or not PASSWORD_HASH.fullmatch(record.password_hash) ): @@ -168,6 +178,8 @@ def configured_mail_account(mailbox): ) return None + if os.path.lexists(rotation_path(path)): + raise ValueError(ROTATION_IN_PROGRESS) record = load_credentials(path) check_registered_manifest(record, mailbox) if not home_is_prepared(record): @@ -250,8 +262,14 @@ def install_mailbox(mailbox, state_directory): None, ) if active is not None: + if os.path.lexists(rotation_path(active.path)): + raise ValueError(ROTATION_IN_PROGRESS) check_registered_manifest(active, mailbox) - prepared = [record for record in records if home_is_prepared(record)] + prepared = [ + published_mailbox_credentials(record, account, auth_group, modern) + for record in records + if home_is_prepared(record) + ] if mailbox.quota_mib is not None or any( record.mailbox.quota_mib is not None for record in prepared ): @@ -278,17 +296,7 @@ def install_mailbox(mailbox, state_directory): "The mailbox already exists outside Coulobre's registry." ) password = secrets.token_urlsafe(32) - password_hash = run( - "doveadm", - "pw", - "-s", - "SHA512-CRYPT", - standard_input=f"{password}\n{password}\n", - ) - if not PASSWORD_HASH.fullmatch(password_hash): - raise ValueError( - "Dovecot did not return the expected password hash." - ) + password_hash = hash_mailbox_password(password) active = Credentials(mailbox, password, password_hash) active.save() os.fsync(state_directory) @@ -309,6 +317,46 @@ def install_mailbox(mailbox, state_directory): return active.path +def hash_mailbox_password(password): + password_hash = run( + "doveadm", + "pw", + "-s", + "SHA512-CRYPT", + standard_input=f"{password}\n{password}\n", + ) + if not PASSWORD_HASH.fullmatch(password_hash): + raise ValueError("Dovecot did not return the expected password hash.") + return password_hash + + +def replacement_credentials(record, pending): + password_hash = pending.get("password_hash") + if ( + not isinstance(password_hash, str) + or not PASSWORD_HASH.fullmatch(password_hash) + or record.rotation_id not in (pending["previous"], pending["id"]) + ): + raise ValueError("The pending mailbox credential record is invalid.") + return replace( + record, + password=pending["password"], + password_hash=password_hash, + rotation_id=pending["id"], + ) + + +def published_mailbox_credentials(record, account, auth_group, modern): + pending = load_pending_rotation(record.path) + if pending is None: + return record + replacement = replacement_credentials(record, pending) + table = read_lookup_table(DOVECOT_USERS, 0o640, auth_group) + replacement_row = dovecot_lookup_row(replacement, account, modern=modern) + # Preserve the live row while another mailbox's rotation is retried. + return replacement if replacement_row in table.splitlines() else record + + def check_registered_manifest(record, mailbox): if record.mailbox != mailbox: raise ValueError( diff --git a/src/coulobre/mail_node_quota.py b/src/coulobre/mail_node_quota.py index 0a41b57..4c2c312 100644 --- a/src/coulobre/mail_node_quota.py +++ b/src/coulobre/mail_node_quota.py @@ -3,6 +3,7 @@ import time from dataclasses import replace from . import mail_node_apply as mail +from .credential_rotation import ROTATION_IN_PROGRESS, rotation_path from .node_files import require_root_directory @@ -21,6 +22,8 @@ def update_mailbox(mailbox, *, suspended=None): path = mail.credential_path(mailbox) if state_directory is None or not os.path.lexists(path): raise ValueError("Apply the mailbox manifest before updating it.") + if os.path.lexists(rotation_path(path)): + raise ValueError(ROTATION_IN_PROGRESS) original = mail.load_credentials(path) if suspended is None: updated = replace(original, mailbox=mailbox) diff --git a/src/coulobre/mail_node_rotation.py b/src/coulobre/mail_node_rotation.py new file mode 100644 index 0000000..e96cb2f --- /dev/null +++ b/src/coulobre/mail_node_rotation.py @@ -0,0 +1,60 @@ +import time + +from . import mail_node_apply as mail +from .credential_rotation import ( + finish_rotation, + load_pending_rotation, + stage_rotation, +) +from .mail_node_quota import publish_mailbox_update + + +def rotate_mailbox_credentials(request): + mailbox = request.resource + path = mail.credential_path(mailbox) + with mail.locked_state(create=False, exclusive=True) as directory: + if directory is None: + raise ValueError( + "Apply the mailbox manifest before rotating its login." + ) + original = mail.load_credentials(path) + mail.check_registered_manifest(original, mailbox) + if original.suspended: + raise ValueError( + "Resume the mailbox before rotating its password." + ) + if load_pending_rotation(path) is None: + mail.configured_mail_account(mailbox) + pending = stage_rotation( + path, + request, + original.rotation_id, + hash_password=mail.hash_mailbox_password, + ) + if original.rotation_id != request.rotation_id: + updated = mail.replacement_credentials(original, pending) + publish_mailbox_update(original, updated, access_change=False) + verify_mailbox_rotation(original, updated) + updated.save(replace=True) + else: + updated = original + publish_mailbox_update(updated, updated, access_change=False) + if not mail.mailbox_can_authenticate(updated): + raise ValueError( + "Dovecot could not authenticate the saved login." + ) + finish_rotation(path) + return {"user": mailbox.address, "password": updated.password} + + +def verify_mailbox_rotation(original, updated): + for _ in range(10): + mail.run("doveadm", "auth", "cache", "flush", updated.mailbox.address) + if mail.mailbox_can_authenticate( + updated + ) and not mail.mailbox_can_authenticate(original): + return + time.sleep(0.2) + raise ValueError( + "Dovecot did not confirm the replacement mailbox password." + ) diff --git a/src/coulobre/service_credentials.py b/src/coulobre/service_credentials.py index 4232d3a..2436055 100644 --- a/src/coulobre/service_credentials.py +++ b/src/coulobre/service_credentials.py @@ -1,19 +1,40 @@ +import argparse import os from dataclasses import dataclass +from .credential_rotation import valid_generation from .database_node import DEFAULT_SOCKET, DatabaseSpec from .mail_node import MailboxSpec from .node_requests import serve_apply_request REQUEST_VERSION = 1 CREDENTIAL_SOCKET = "/run/coulobre-service-credentials.sock" +MAIL_CREDENTIAL_SOCKET = "/run/coulobre-mail-credentials.sock" CREDENTIAL_TIMEOUT_SECONDS = 15 +ROTATION_TIMEOUT_SECONDS = 25 CREDENTIALS_UNAVAILABLE = "The service credentials are currently unavailable." @dataclass(frozen=True) class ServiceCredentialRequest: resource: DatabaseSpec | MailboxSpec + operation: str = "read" + rotation_id: str | None = None + previous_id: str | None = None + + def __post_init__(self): + if self.operation in ("read", "generation"): + if self.rotation_id is None and self.previous_id is None: + return + elif ( + self.operation == "rotate" + and isinstance(self.rotation_id, str) + and valid_generation(self.rotation_id) + and valid_generation(self.previous_id) + and self.rotation_id != self.previous_id + ): + return + raise ValueError("Expected a valid credential operation.") @property def kind(self): @@ -27,31 +48,62 @@ class ServiceCredentialRequest: def from_manifest(cls, data): if ( not isinstance(data, dict) - or data.keys() != {"version", "kind", "resource"} - or type(data["version"]) is not int + or type(data.get("version")) is not int or data["version"] != REQUEST_VERSION ): - raise ValueError("Expected a local service credential request.") - if data["kind"] == "database": - return cls(DatabaseSpec.from_manifest(data["resource"])) - if data["kind"] == "mailbox": - return cls(MailboxSpec.from_manifest(data["resource"])) - raise ValueError("Expected a database or mailbox credential request.") + raise ValueError("Expected a service credential request.") + fields = {"version", "kind", "resource"} + operation = data.get("operation", "read") + if operation == "generation": + fields.add("operation") + elif operation == "rotate": + fields.update(("operation", "rotation_id", "previous_id")) + if data.keys() != fields: + raise ValueError("Expected a service credential request.") + parsers = { + "database": DatabaseSpec.from_manifest, + "mailbox": MailboxSpec.from_manifest, + } + kind = data["kind"] + if not isinstance(kind, str) or kind not in parsers: + raise ValueError( + "Expected a database or mailbox credential request." + ) + return cls( + parsers[kind](data["resource"]), + operation, + data.get("rotation_id"), + data.get("previous_id"), + ) def manifest(self): - return { + manifest = { "version": REQUEST_VERSION, "kind": self.kind, "resource": self.resource.manifest(), } + if self.operation != "read": + manifest["operation"] = self.operation + if self.operation == "rotate": + manifest.update( + rotation_id=self.rotation_id, previous_id=self.previous_id + ) + return manifest -def main(): +def main(argv=None): + parser = argparse.ArgumentParser() + parser.add_argument("--mailbox-only", action="store_true") + args = parser.parse_args(argv) + + def parse(payload): + request = ServiceCredentialRequest.from_manifest(payload) + if args.mailbox_only and request.kind != "mailbox": + raise ValueError("This node handles mailbox requests only.") + return request + return serve_apply_request( - REQUEST_VERSION, - ServiceCredentialRequest.from_manifest, - read_service_credentials, - include_result=True, + REQUEST_VERSION, parse, read_service_credentials, include_result=True ) @@ -61,26 +113,55 @@ def read_service_credentials(request): setting = f"COULOBRE_LOCAL_{request.kind.upper()}_CREDENTIALS" if os.environ.get(setting) != "1": raise ValueError(CREDENTIALS_UNAVAILABLE) + if ( + request.operation != "read" + and os.environ.get(f"{setting}_ROTATION") != "1" + ): + raise ValueError(CREDENTIALS_UNAVAILABLE) try: - if request.kind == "database": - return read_database_credentials(request.resource) - return read_mailbox_credentials(request.resource) + if request.operation == "rotate": + return rotate_service_credentials(request) + read = ( + read_database_credentials + if request.kind == "database" + else read_mailbox_credentials + ) + if request.operation == "generation": + return {"generation": read(request.resource, generation_only=True)} + return read(request.resource) except (OSError, ValueError): raise ValueError(CREDENTIALS_UNAVAILABLE) from None -def read_database_credentials(database): +def rotate_service_credentials(request): + if request.kind == "database": + from .database_node_rotation import rotate_database_credentials + + record = rotate_database_credentials(request, DEFAULT_SOCKET) + return { + key: record[key] + for key in ("database", "user", "host", "socket", "password") + } + + from .mail_node_rotation import rotate_mailbox_credentials + + return rotate_mailbox_credentials(request) + + +def read_database_credentials(database, *, generation_only=False): from .database_node_backup import managed_database with managed_database(database, DEFAULT_SOCKET) as (_, record, _path): + if generation_only: + return record.get("rotation_id") return { key: record[key] for key in ("database", "user", "host", "socket", "password") } -def read_mailbox_credentials(mailbox): +def read_mailbox_credentials(mailbox, *, generation_only=False): from .mail_node_apply import ( configured_mail_account, credential_path, @@ -92,4 +173,6 @@ def read_mailbox_credentials(mailbox): if configured_mail_account(mailbox) is None: raise ValueError(CREDENTIALS_UNAVAILABLE) credentials = load_credentials(credential_path(mailbox)) + if generation_only: + return credentials.rotation_id return {"user": mailbox.address, "password": credentials.password} From 651f041e84f47bc181d72b91fbbcf336e5a26137 Mon Sep 17 00:00:00 2001 From: Peter van Arkel Date: Sat, 21 Nov 2026 19:23:01 +0100 Subject: [PATCH 2/3] Confirm and audit credential rotation in the panel --- src/coulobre/hosting/credential_views.py | 161 +++++++++++++- .../0036_credential_rotation_audit.py | 75 +++++++ src/coulobre/hosting/models.py | 7 + src/coulobre/hosting/resource_requests.py | 13 ++ src/coulobre/hosting/service_changes.py | 5 + src/coulobre/hosting/service_credentials.py | 164 +++++++++++++- .../hosting/service_credentials.html | 25 ++- .../hosting/test_credential_rotation.py | 207 ++++++++++++++++++ src/coulobre/hosting/urls.py | 10 + src/coulobre/settings.py | 12 + 10 files changed, 662 insertions(+), 17 deletions(-) create mode 100644 src/coulobre/hosting/migrations/0036_credential_rotation_audit.py create mode 100644 src/coulobre/hosting/test_credential_rotation.py diff --git a/src/coulobre/hosting/credential_views.py b/src/coulobre/hosting/credential_views.py index 2e5410c..0c4aeda 100644 --- a/src/coulobre/hosting/credential_views.py +++ b/src/coulobre/hosting/credential_views.py @@ -1,7 +1,11 @@ from django.conf import settings from django.contrib.auth.mixins import PermissionRequiredMixin +from django.core.exceptions import ValidationError +from django.core.signing import BadSignature +from django.db import transaction from django.http import Http404 from django.shortcuts import get_object_or_404 +from django.urls import reverse from django.utils.decorators import method_decorator from django.utils.functional import cached_property from django.views.decorators.cache import never_cache @@ -12,14 +16,28 @@ from django.views.decorators.debug import ( from django.views.generic import FormView from .access import customer_for_user -from .models import HostingDatabase, HostingMailbox, ServiceCredentialAccess +from .models import ( + HostingAccount, + HostingDatabase, + HostingMailbox, + ServiceCredentialAccess, +) +from .resource_requests import lock_hosting_account, require_active_services from .service_credentials import ( ConfirmCredentialAccessForm, + ConfirmCredentialRotationForm, CredentialKind, + CredentialMethod, CredentialOutcome, can_reveal_credentials, + can_rotate_credentials, enabled_credential_access, + enabled_rotation, fetch_service_credentials, + parse_rotation, + reserve_rotation, + rotation_history, + rotation_ticket, verify_credential_access, ) @@ -29,10 +47,13 @@ from .service_credentials import ( class ServiceCredentialView(PermissionRequiredMixin, FormView): form_class = ConfirmCredentialAccessForm template_name = "hosting/service_credentials.html" + rotating = False def dispatch(self, request, *args, **kwargs): if not enabled_credential_access(request, self.kind): raise Http404 + if self.rotating and not enabled_rotation(request, self.kind): + raise Http404 if getattr(request, "impersonation", None) is not None: return self.handle_no_permission() response = super().dispatch(request, *args, **kwargs) @@ -40,7 +61,38 @@ class ServiceCredentialView(PermissionRequiredMixin, FormView): return response def has_permission(self): - return can_reveal_credentials(self.request.user, self.kind) + check = ( + can_rotate_credentials if self.rotating else can_reveal_credentials + ) + return check(self.request.user, self.kind) + + def get_form_class(self): + if self.rotating: + return ConfirmCredentialRotationForm + return super().get_form_class() + + @cached_property + def customer_id(self): + customer = customer_for_user(self.request.user) + return customer.pk if customer is not None else None + + def get(self, request, *args, **kwargs): + if not self.rotating: + return super().get(request, *args, **kwargs) + try: + require_active_services(self.account) + require_finished_provisioning(self.resource) + form = self.get_form() + form.initial["ticket"] = rotation_ticket( + self.resource, self.account.pk, request.user.pk + ) + except ValidationError as error: + return self.rotation_problem(" ".join(error.messages), status=409) + except (OSError, ValueError): + return self.rotation_problem( + "The credential node is currently unavailable.", status=503 + ) + return self.render_to_response(self.get_context_data(form=form)) def get_queryset(self): customer = customer_for_user(self.request.user) @@ -55,18 +107,54 @@ class ServiceCredentialView(PermissionRequiredMixin, FormView): return get_object_or_404(self.get_queryset(), pk=self.kwargs["pk"]) def get_context_data(self, **kwargs): - return super().get_context_data( - account=self.account, resource=self.resource, **kwargs + context = super().get_context_data( + account=self.account, + resource=self.resource, + rotating=self.rotating, + database=self.kind == CredentialKind.DATABASE, + **kwargs, + ) + if ( + not self.rotating + and enabled_rotation(self.request, self.kind) + and can_rotate_credentials(self.request.user, self.kind) + ): + context["rotation_url"] = reverse( + f"panel:{self.kind}_credential_rotation", + args=[self.resource.pk], + ) + return context + + def rotation_problem(self, message, *, status): + return self.render_to_response( + self.get_context_data(rotation_problem=message), status=status ) @sensitive_variables() def form_valid(self, form): + rotation = None + if self.rotating: + try: + rotation = parse_rotation( + form.cleaned_data["ticket"], + self.resource, + self.account.pk, + self.request.user, + ) + except (BadSignature, ValueError): + return self.rotation_problem( + "Open a new password change form for this resource.", + status=409, + ) event = verify_credential_access( self.request.user, form.cleaned_data["password"], kind=self.kind, resource=str(self.resource), account_id=self.account.pk, + method=CredentialMethod.ROTATE + if self.rotating + else CredentialMethod.REVEAL, ) if event is None: form.add_error( @@ -82,6 +170,9 @@ class ServiceCredentialView(PermissionRequiredMixin, FormView): form.add_error("password", "Enter your current panel password.") return self.form_invalid(form) + if self.rotating: + return self.rotate(form, event, rotation) + spec = self.resource.spec events = ServiceCredentialAccess.objects.filter(pk=event.pk) try: @@ -106,6 +197,68 @@ class ServiceCredentialView(PermissionRequiredMixin, FormView): events.update(outcome=CredentialOutcome.REVEALED) return response + @sensitive_variables() + def rotate(self, form, event, rotation): + try: + reserve_rotation(event, rotation, self.customer_id) + with transaction.atomic(): + account = lock_hosting_account( + event.hosting_account_id, self.customer_id + ) + require_active_services(account) + current = ( + self.get_queryset().filter(pk=self.resource.pk).first() + ) + if current is None or current.spec != rotation.resource: + raise Http404 + require_finished_provisioning(current) + latest = rotation_history( + account.pk, event.kind, event.resource + ).first() + if str(latest.rotation_id) != rotation.rotation_id: + raise ValidationError( + "Open a new password change form for this resource." + ) + try: + credentials = fetch_service_credentials( + current.spec, rotation + ) + except (OSError, ValueError): + event.outcome = CredentialOutcome.UNAVAILABLE + event.save(update_fields=["outcome"]) + form.add_error( + None, + "The password change could not be confirmed. " + "Retry this request.", + ) + return self.render_to_response( + self.get_context_data(form=form), status=503 + ) + event.outcome = CredentialOutcome.ROTATED + event.save(update_fields=["outcome"]) + except (HostingAccount.DoesNotExist, Http404) as error: + mark_rotation_blocked(event) + raise Http404 from error + except ValidationError as error: + mark_rotation_blocked(event) + return self.rotation_problem(" ".join(error.messages), status=409) + return self.render_to_response( + self.get_context_data(fields=self.connection_fields(credentials)) + ).render() + + +def mark_rotation_blocked(event): + event.outcome = CredentialOutcome.BLOCKED + event.save(update_fields=["outcome"]) + + +def require_finished_provisioning(resource): + provisioning = getattr(resource, "provisioning", None) + if provisioning is not None and provisioning.state != "configured": + raise ValidationError( + "Complete provisioning before changing the resource password." + ) + class DatabaseCredentialView(ServiceCredentialView): kind = CredentialKind.DATABASE diff --git a/src/coulobre/hosting/migrations/0036_credential_rotation_audit.py b/src/coulobre/hosting/migrations/0036_credential_rotation_audit.py new file mode 100644 index 0000000..d7fc853 --- /dev/null +++ b/src/coulobre/hosting/migrations/0036_credential_rotation_audit.py @@ -0,0 +1,75 @@ +# Generated by Django 5.2.19 on 2026-11-21 18:15 + +from django.db import migrations, models + + +class Migration(migrations.Migration): + dependencies = [ + ("hosting", "0035_reseller_audit_event"), + ] + + operations = [ + migrations.AlterModelOptions( + name="servicecredentialaccess", + options={ + "default_permissions": ("view",), + "ordering": ("-requested_at", "-pk"), + "permissions": [ + ( + "reveal_database_credentials", + "Can reveal database credentials", + ), + ( + "reveal_mailbox_credentials", + "Can reveal mailbox credentials", + ), + ( + "rotate_database_credentials", + "Can rotate database credentials", + ), + ( + "rotate_mailbox_credentials", + "Can rotate mailbox credentials", + ), + ], + }, + ), + migrations.AddField( + model_name="servicecredentialaccess", + name="previous_rotation_id", + field=models.UUIDField(null=True), + ), + migrations.AddField( + model_name="servicecredentialaccess", + name="rotation_id", + field=models.UUIDField(null=True), + ), + migrations.AlterField( + model_name="servicecredentialaccess", + name="method", + field=models.CharField( + choices=[ + ("reveal", "Show connection details"), + ("phpmyadmin", "phpMyAdmin"), + ("rotate", "Rotate password"), + ], + default="reveal", + max_length=10, + ), + ), + migrations.AlterField( + model_name="servicecredentialaccess", + name="outcome", + field=models.CharField( + choices=[ + ("requested", "Requested"), + ("rejected", "Password confirmation failed"), + ("unavailable", "Credentials unavailable"), + ("revealed", "Credentials revealed"), + ("rotated", "Password changed"), + ("blocked", "Password change was blocked"), + ], + max_length=11, + ), + ), + ] diff --git a/src/coulobre/hosting/models.py b/src/coulobre/hosting/models.py index dd36efc..130a534 100644 --- a/src/coulobre/hosting/models.py +++ b/src/coulobre/hosting/models.py @@ -165,10 +165,13 @@ class ServiceCredentialAccess(models.Model): REJECTED = "rejected", "Password confirmation failed" UNAVAILABLE = "unavailable", "Credentials unavailable" REVEALED = "revealed", "Credentials revealed" + ROTATED = "rotated", "Password changed" + BLOCKED = "blocked", "Password change was blocked" class Method(models.TextChoices): REVEAL = "reveal", "Show connection details" PHPMYADMIN = "phpmyadmin", "phpMyAdmin" + ROTATE = "rotate", "Rotate password" method = models.CharField( max_length=10, choices=Method, default=Method.REVEAL @@ -178,6 +181,8 @@ class ServiceCredentialAccess(models.Model): ) actor_username = models.CharField(max_length=150) hosting_account_id = models.PositiveBigIntegerField() + rotation_id = models.UUIDField(null=True) + previous_rotation_id = models.UUIDField(null=True) kind = models.CharField(max_length=8, choices=Kind) resource = models.CharField(max_length=254) requested_at = models.DateTimeField(default=timezone.now) @@ -190,6 +195,8 @@ class ServiceCredentialAccess(models.Model): permissions = [ ("reveal_database_credentials", "Can reveal database credentials"), ("reveal_mailbox_credentials", "Can reveal mailbox credentials"), + ("rotate_database_credentials", "Can rotate database credentials"), + ("rotate_mailbox_credentials", "Can rotate mailbox credentials"), ] diff --git a/src/coulobre/hosting/resource_requests.py b/src/coulobre/hosting/resource_requests.py index 44b7809..3829975 100644 --- a/src/coulobre/hosting/resource_requests.py +++ b/src/coulobre/hosting/resource_requests.py @@ -135,6 +135,19 @@ def change_mailbox_quota(mailbox, quota_mib): ) require_active_services(account) current = HostingMailbox.objects.get(pk=mailbox.pk) + from .service_credentials import ( + UNCONFIRMED_ROTATION, + CredentialKind, + rotation_history, + ) + + latest = rotation_history( + account.pk, CredentialKind.MAILBOX, str(current) + ).first() + if latest is not None and latest.outcome in UNCONFIRMED_ROTATION: + raise ValidationError( + "Finish the mailbox password change before changing its quota." + ) if current.quota_mib == quota_mib: return diff --git a/src/coulobre/hosting/service_changes.py b/src/coulobre/hosting/service_changes.py index aab5b75..cadad14 100644 --- a/src/coulobre/hosting/service_changes.py +++ b/src/coulobre/hosting/service_changes.py @@ -19,6 +19,7 @@ from .models import ( ) from .node_client import apply_on_local_node from .resource_requests import lock_hosting_account +from .service_credentials import unresolved_rotation_exists Kind = AccountServiceJob.Kind @@ -43,6 +44,10 @@ SERVICES = { def current_service_jobs(account): + if unresolved_rotation_exists(account.pk): + raise ValidationError( + "Finish the pending or unconfirmed password change first." + ) activations = WebActivation.objects.filter(plan__account=account) databases = DatabaseProvisioning.objects.filter(database__account=account) mailboxes = MailboxProvisioning.objects.filter( diff --git a/src/coulobre/hosting/service_credentials.py b/src/coulobre/hosting/service_credentials.py index 12b4075..1b7c16e 100644 --- a/src/coulobre/hosting/service_credentials.py +++ b/src/coulobre/hosting/service_credentials.py @@ -1,29 +1,41 @@ from datetime import timedelta +from uuid import uuid4 from django import forms from django.conf import settings from django.contrib.auth import get_user_model -from django.core.exceptions import PermissionDenied +from django.core import signing +from django.core.exceptions import PermissionDenied, ValidationError from django.db import connection, transaction from django.db.models import F from django.utils import timezone from django.views.decorators.debug import sensitive_variables +from coulobre.credential_rotation import valid_generation from coulobre.service_credentials import ( CREDENTIAL_SOCKET, CREDENTIAL_TIMEOUT_SECONDS, CREDENTIALS_UNAVAILABLE, + MAIL_CREDENTIAL_SOCKET, + ROTATION_TIMEOUT_SECONDS, ServiceCredentialRequest, ) from .access import customer_for_user, reseller_for_user from .models import ServiceCredentialAccess from .node_client import apply_on_local_node +from .resource_requests import lock_hosting_account, require_active_services ATTEMPT_LIMIT = 5 ATTEMPT_WINDOW = timedelta(minutes=5) CredentialKind = ServiceCredentialAccess.Kind CredentialOutcome = ServiceCredentialAccess.Outcome +CredentialMethod = ServiceCredentialAccess.Method +ROTATION_TICKET_SALT = "coulobre.credential-rotation" +UNCONFIRMED_ROTATION = ( + CredentialOutcome.REQUESTED, + CredentialOutcome.UNAVAILABLE, +) CREDENTIAL_PERMISSIONS = { CredentialKind.DATABASE: ( @@ -37,6 +49,10 @@ CREDENTIAL_PERMISSIONS = { "hosting.reveal_mailbox_credentials", ), } +ROTATION_PERMISSIONS = { + CredentialKind.DATABASE: "hosting.rotate_database_credentials", + CredentialKind.MAILBOX: "hosting.rotate_mailbox_credentials", +} class ConfirmCredentialAccessForm(forms.Form): @@ -53,7 +69,20 @@ def enabled_credential_access(request, kind): return False if kind == CredentialKind.DATABASE: return settings.LOCAL_DATABASE_CREDENTIALS - return settings.LOCAL_MAILBOX_CREDENTIALS + return ( + settings.REMOTE_MAILBOX_CREDENTIALS + or settings.LOCAL_MAILBOX_CREDENTIALS + ) + + +def enabled_rotation(request, kind): + if not enabled_credential_access(request, kind): + return False + if kind == CredentialKind.DATABASE: + return settings.LOCAL_DATABASE_CREDENTIAL_ROTATION + if settings.REMOTE_MAILBOX_CREDENTIALS: + return settings.REMOTE_MAILBOX_CREDENTIAL_ROTATION + return settings.LOCAL_MAILBOX_CREDENTIAL_ROTATION def can_reveal_credentials(user, kind): @@ -66,9 +95,24 @@ def can_reveal_credentials(user, kind): return user.has_perms(CREDENTIAL_PERMISSIONS[kind]) +def can_rotate_credentials(user, kind): + return can_reveal_credentials(user, kind) and ( + customer_for_user(user) is not None + or user.has_perm(ROTATION_PERMISSIONS[kind]) + ) + + @transaction.atomic @sensitive_variables() -def verify_credential_access(user, password, *, kind, resource, account_id): +def verify_credential_access( + user, + password, + *, + kind, + resource, + account_id, + method=CredentialMethod.REVEAL, +): users = get_user_model().objects.filter(pk=user.pk, is_active=True) if connection.vendor == "sqlite": # Serialize confirmations before counting failed attempts. @@ -89,6 +133,7 @@ def verify_credential_access(user, password, *, kind, resource, account_id): accepted = actor.check_password(password) return ServiceCredentialAccess.objects.create( actor=actor, + method=method, actor_username=actor.get_username(), hosting_account_id=account_id, kind=kind, @@ -101,15 +146,28 @@ def verify_credential_access(user, password, *, kind, resource, account_id): @sensitive_variables() -def fetch_service_credentials(resource): - spec = ServiceCredentialRequest(resource) - reply = apply_on_local_node( +def send_credential_request(spec): + remote = ( + spec.kind == CredentialKind.MAILBOX + and settings.REMOTE_MAILBOX_CREDENTIALS + ) + return apply_on_local_node( spec, - CREDENTIAL_SOCKET, + MAIL_CREDENTIAL_SOCKET if remote else CREDENTIAL_SOCKET, "credential node", "service credential request", - timeout=CREDENTIAL_TIMEOUT_SECONDS, + timeout=( + ROTATION_TIMEOUT_SECONDS + if spec.operation == "rotate" + else CREDENTIAL_TIMEOUT_SECONDS + ), ) + + +@sensitive_variables() +def fetch_service_credentials(resource, rotation=None): + spec = ServiceCredentialRequest(resource) if rotation is None else rotation + reply = send_credential_request(spec) keys = ("user", "password") if spec.kind == CredentialKind.DATABASE: keys += ("database", "host", "socket") @@ -128,3 +186,93 @@ def fetch_service_credentials(resource): ) or any(reply[key] != value for key, value in expected.items()): raise ValueError(CREDENTIALS_UNAVAILABLE) return {key: reply[key] for key in keys} + + +class ConfirmCredentialRotationForm(ConfirmCredentialAccessForm): + ticket = forms.CharField(max_length=500, widget=forms.HiddenInput) + + +def rotation_history(account_id, kind=None, resource=None): + events = ServiceCredentialAccess.objects.filter( + hosting_account_id=account_id, + method=CredentialMethod.ROTATE, + rotation_id__isnull=False, + ).exclude(outcome=CredentialOutcome.BLOCKED) + if kind is not None: + events = events.filter(kind=kind, resource=resource) + return events.order_by("-pk") + + +def unresolved_rotation_exists(account_id): + seen = set() + for event in rotation_history(account_id).values_list( + "kind", "resource", "outcome" + ): + kind, resource, outcome = event + target = kind, resource + if target not in seen and outcome in UNCONFIRMED_ROTATION: + return True + seen.add(target) + return False + + +@sensitive_variables() +def rotation_ticket(resource, account_id, user_id): + manifest = ServiceCredentialRequest(resource.spec, "generation") + last = rotation_history(account_id, manifest.kind, str(resource)).first() + if last is not None and last.outcome in UNCONFIRMED_ROTATION: + rotation_id = str(last.rotation_id) + previous_id = ( + str(last.previous_rotation_id) + if last.previous_rotation_id + else None + ) + else: + reply = send_credential_request(manifest) + if "generation" not in reply or not valid_generation( + reply["generation"] + ): + raise ValueError(CREDENTIALS_UNAVAILABLE) + rotation_id, previous_id = str(uuid4()), reply["generation"] + return signing.dumps( + [ + account_id, + manifest.kind, + resource.pk, + user_id, + rotation_id, + previous_id, + ], + salt=ROTATION_TICKET_SALT, + ) + + +def parse_rotation(ticket, resource, account_id, actor): + payload = signing.loads(ticket, salt=ROTATION_TICKET_SALT, max_age=3600) + if not isinstance(payload, list) or len(payload) != 6: + raise signing.BadSignature + rotation = ServiceCredentialRequest(resource.spec, "rotate", *payload[4:]) + if payload[:4] != [account_id, rotation.kind, resource.pk, actor.pk]: + raise signing.BadSignature + return rotation + + +@transaction.atomic +def reserve_rotation(event, rotation, customer_id): + account = lock_hosting_account(event.hosting_account_id, customer_id) + require_active_services(account) + latest = rotation_history(account.pk, event.kind, event.resource).first() + if ( + latest is not None + and str(latest.rotation_id) != rotation.rotation_id + and ( + latest.outcome in UNCONFIRMED_ROTATION + or str(latest.rotation_id) != rotation.previous_id + ) + ): + raise ValidationError( + "Open a new password change form for this resource." + ) + event.rotation_id = rotation.rotation_id + event.previous_rotation_id = rotation.previous_id + event.save(update_fields=["rotation_id", "previous_rotation_id"]) diff --git a/src/coulobre/hosting/templates/hosting/service_credentials.html b/src/coulobre/hosting/templates/hosting/service_credentials.html index 52daf47..2981902 100644 --- a/src/coulobre/hosting/templates/hosting/service_credentials.html +++ b/src/coulobre/hosting/templates/hosting/service_credentials.html @@ -1,17 +1,24 @@ {% extends "hosting/base.html" %} {% load static %} -{% block title %}Connection details · Coulobre Panel{% endblock %} +{% block title %}{% if rotating %}Rotate password{% else %}Connection details{% endif %} · Coulobre Panel{% endblock %} {% block content %} ← {{ account.name }}
-

Connection details

+

{% if rotating %}Rotate password{% else %}Connection details{% endif %}

{{ resource }}

- {% if fields %} + {% if rotation_problem %} +

{{ rotation_problem }}

+ Back to hosting account + {% elif fields %}
+ {% if rotating %} + {% if database %}

Password changed. Update the database password in each application that uses this login.

+ {% else %}

Password changed. Update the saved login in your mail clients.

{% endif %} + {% endif %} {% for key, label, value in fields %}
@@ -24,16 +31,24 @@

Done + {% if rotation_url %}Rotate password{% endif %}
{% else %}
-

Confirm your current panel password to show the service login.

+ {% if rotating %} +

Confirm your panel password to generate a replacement password for this login.

+ {% if database %}

Applications using the previous password will need the new one when they reconnect.

+ {% else %}

Mail clients using the previous password will need the new one when they reconnect.

{% endif %} + {% else %} +

Confirm your current panel password to show the service login.

+ {% endif %} {% csrf_token %} {{ form.as_div }}
- + + {% if rotation_url %}Rotate password{% endif %} Cancel
diff --git a/src/coulobre/hosting/test_credential_rotation.py b/src/coulobre/hosting/test_credential_rotation.py new file mode 100644 index 0000000..0b30204 --- /dev/null +++ b/src/coulobre/hosting/test_credential_rotation.py @@ -0,0 +1,207 @@ +from pathlib import Path +from tempfile import TemporaryDirectory +from unittest.mock import patch +from uuid import uuid4 + +from django.contrib.auth import get_user_model +from django.test import SimpleTestCase, TestCase, override_settings +from django.urls import reverse + +from coulobre.credential_rotation import finish_rotation, stage_rotation +from coulobre.database_node import DatabaseSpec +from coulobre.service_credentials import ( + CREDENTIAL_SOCKET, + MAIL_CREDENTIAL_SOCKET, + ServiceCredentialRequest, +) + +from .models import ( + Customer, + HostingAccount, + HostingMailbox, + HostingMailDomain, + ServiceCredentialAccess, +) + +PASSWORD = "fixture-password-for-panel" +REPLACEMENT = "fixture-service-credential" +Outcome = ServiceCredentialAccess.Outcome + + +@override_settings( + DEBUG=False, + LOCAL_DATABASE_CREDENTIALS=True, + LOCAL_DATABASE_CREDENTIAL_ROTATION=True, + REMOTE_MAILBOX_CREDENTIALS=True, + REMOTE_MAILBOX_CREDENTIAL_ROTATION=True, +) +class CredentialRotationTests(TestCase): + @classmethod + def setUpTestData(cls): + users = get_user_model().objects + cls.owner = users.create_user("customer", password=PASSWORD) + customer = Customer.objects.create(user=cls.owner) + cls.account = HostingAccount.objects.create( + name="Own", primary_domain="own.example", customer=customer + ) + cls.database = cls.account.databases.create(suffix="app") + cls.second_database = cls.account.databases.create(suffix="shop") + other = HostingAccount.objects.create( + name="Other", primary_domain="other.example" + ) + cls.other_database = other.databases.create(suffix="app") + domain = HostingMailDomain.objects.create( + account=cls.account, domain=cls.account.primary_domain + ) + cls.mailbox = HostingMailbox.objects.create( + mail_domain=domain, local_part="support" + ) + + def setUp(self): + self.client.force_login(self.owner) + + def url(self, kind, target): + return reverse(f"panel:{kind}_credential_rotation", args=[target.pk]) + + def submit(self, url, ticket, password=PASSWORD): + return self.client.post( + url, {"password": password, "ticket": ticket}, secure=True + ) + + def test_scope_confirmation_and_database_result(self): + database = self.database + url = self.url("database", database) + reply = { + "database": database.spec.name, + "user": database.spec.name, + "host": "localhost", + "socket": "/run/mysqld/mysqld.sock", + "password": REPLACEMENT, + } + with patch( + "coulobre.hosting.service_credentials.apply_on_local_node", + side_effect=[{"generation": None}, reply], + ) as node: + form = self.client.get(url, secure=True) + ticket = form.context["form"]["ticket"].value() + self.assertNotContains(form, REPLACEMENT) + self.assertContains( + self.submit( + self.url("database", self.second_database), ticket + ), + "Open a new password change form", + status_code=409, + ) + self.assertEqual( + self.submit( + self.url("database", self.other_database), ticket + ).status_code, + 404, + ) + self.assertContains( + self.submit(url, ticket, "incorrect"), + "Enter your current panel password.", + ) + self.assertEqual(node.call_count, 1) + result = self.submit(url, ticket) + self.assertContains(result, REPLACEMENT) + self.assertNotContains(result, PASSWORD) + self.assertIn("no-store", result.headers["Cache-Control"]) + request, socket, *_ = node.call_args.args + self.assertEqual(socket, CREDENTIAL_SOCKET) + self.assertEqual(request.operation, "rotate") + self.assertEqual(request.resource, database.spec) + attempts = ServiceCredentialAccess.objects.order_by("pk") + self.assertEqual( + list(attempts.values_list("outcome", flat=True)), + [Outcome.REJECTED, Outcome.ROTATED], + ) + self.assertNotIn(REPLACEMENT, str(list(attempts.values()))) + + def test_remote_mail_retry_reuses_the_request_after_a_lost_response(self): + url = self.url("mailbox", self.mailbox) + reply = {"user": self.mailbox.spec.address, "password": REPLACEMENT} + with patch( + "coulobre.hosting.service_credentials.apply_on_local_node", + side_effect=[{"generation": None}, OSError, reply], + ) as node: + form = self.client.get(url, secure=True) + ticket = form.context["form"]["ticket"].value() + self.assertContains( + self.submit(url, ticket), + "could not be confirmed", + status_code=503, + ) + reopened = self.client.get(url, secure=True) + self.assertContains( + self.submit(url, reopened.context["form"]["ticket"].value()), + REPLACEMENT, + ) + self.assertEqual(node.call_count, 3) + self.assertEqual( + [call.args[1] for call in node.call_args_list], + [MAIL_CREDENTIAL_SOCKET] * 3, + ) + self.assertEqual( + node.call_args_list[1].args[0], node.call_args_list[2].args[0] + ) + attempts = ServiceCredentialAccess.objects.order_by("pk") + self.assertEqual( + list(attempts.values_list("outcome", flat=True)), + [Outcome.UNAVAILABLE, Outcome.ROTATED], + ) + self.assertEqual( + attempts.first().rotation_id, attempts.last().rotation_id + ) + + def test_a_stale_form_cannot_change_a_password_again(self): + url = self.url("mailbox", self.mailbox) + reply = {"user": self.mailbox.spec.address, "password": REPLACEMENT} + with patch( + "coulobre.hosting.service_credentials.apply_on_local_node", + side_effect=[{"generation": None}, {"generation": None}, reply], + ) as node: + tickets = [ + self.client.get(url, secure=True) + .context["form"]["ticket"] + .value() + for _ in range(2) + ] + self.assertContains(self.submit(url, tickets[0]), REPLACEMENT) + self.assertContains( + self.submit(url, tickets[1]), + "Open a new password change form", + status_code=409, + ) + self.assertEqual(node.call_count, 3) + self.assertEqual( + ServiceCredentialAccess.objects.first().outcome, Outcome.BLOCKED + ) + + +class NodeRotationStateTests(SimpleTestCase): + def test_a_pending_operation_is_replayed_and_old_generations_are_rejected( + self, + ): + path = Path(self.enterContext(TemporaryDirectory())) / "test.json" + resource = DatabaseSpec(1, "test") + reservation = ServiceCredentialRequest( + resource, "rotate", str(uuid4()) + ) + second = ServiceCredentialRequest(resource, "rotate", str(uuid4())) + with patch( + "coulobre.credential_rotation.read_root_file", + side_effect=lambda path, **kwargs: path.read_text(), + ): + staged = stage_rotation(path, reservation, None) + self.assertEqual(stage_rotation(path, reservation, None), staged) + with self.assertRaisesMessage( + ValueError, "Retry the current credential change" + ): + stage_rotation(path, second, None) + finish_rotation(path) + self.assertIsNone( + stage_rotation(path, reservation, reservation.rotation_id) + ) + with self.assertRaisesMessage(ValueError, "changed after"): + stage_rotation(path, second, reservation.rotation_id) diff --git a/src/coulobre/hosting/urls.py b/src/coulobre/hosting/urls.py index 563dcc3..5cbb379 100644 --- a/src/coulobre/hosting/urls.py +++ b/src/coulobre/hosting/urls.py @@ -163,6 +163,11 @@ urlpatterns = [ DatabaseCredentialView.as_view(), name="database_credentials", ), + path( + "databases//credentials/rotate/", + DatabaseCredentialView.as_view(rotating=True), + name="database_credential_rotation", + ), path( "databases//manifest/", views.DownloadDatabaseManifest.as_view(), @@ -203,6 +208,11 @@ urlpatterns = [ MailboxCredentialView.as_view(), name="mailbox_credentials", ), + path( + "mailboxes//credentials/rotate/", + MailboxCredentialView.as_view(rotating=True), + name="mailbox_credential_rotation", + ), path( "mailboxes//manifest/", views.DownloadMailboxManifest.as_view(), diff --git a/src/coulobre/settings.py b/src/coulobre/settings.py index f947776..00fe385 100644 --- a/src/coulobre/settings.py +++ b/src/coulobre/settings.py @@ -138,6 +138,18 @@ LOCAL_DNS_PUBLISHING = os.environ.get("COULOBRE_LOCAL_DNS_PUBLISHING") == "1" LOCAL_MAILBOX_PROVISIONING = ( os.environ.get("COULOBRE_LOCAL_MAILBOX_PROVISIONING") == "1" ) +REMOTE_MAILBOX_CREDENTIALS = ( + os.environ.get("COULOBRE_REMOTE_MAILBOX_CREDENTIALS") == "1" +) +LOCAL_DATABASE_CREDENTIAL_ROTATION = ( + os.environ.get("COULOBRE_LOCAL_DATABASE_CREDENTIALS_ROTATION") == "1" +) +LOCAL_MAILBOX_CREDENTIAL_ROTATION = ( + os.environ.get("COULOBRE_LOCAL_MAILBOX_CREDENTIALS_ROTATION") == "1" +) +REMOTE_MAILBOX_CREDENTIAL_ROTATION = ( + os.environ.get("COULOBRE_REMOTE_MAILBOX_CREDENTIALS_ROTATION") == "1" +) LOCAL_DATABASE_CREDENTIALS = ( os.environ.get("COULOBRE_LOCAL_DATABASE_CREDENTIALS") == "1" ) From 0ab0eebfc633f1273e7a82bd159770b55c1bc626 Mon Sep 17 00:00:00 2001 From: Peter van Arkel Date: Sat, 21 Nov 2026 19:23:01 +0100 Subject: [PATCH 3/3] Deploy remote mailbox credentials over a dedicated SSH relay --- .../coulobre-mail-credentials.conf.example | 15 +++ .../mail-credential-client.conf.example | 13 +++ deploy/panel.env.example | 4 + .../systemd/coulobre-mail-credentials.socket | 11 ++ .../coulobre-mail-credentials@.service | 20 ++++ .../remote.conf | 9 ++ .../rotation.conf | 4 + .../credentials-remote-mail.conf | 6 + .../database-rotation.conf | 4 + .../mailbox-rotation.conf | 4 + docs/deployment.md | 105 +++++++++++++++++- 11 files changed, 192 insertions(+), 3 deletions(-) create mode 100644 deploy/openssh/coulobre-mail-credentials.conf.example create mode 100644 deploy/openssh/mail-credential-client.conf.example create mode 100644 deploy/systemd/coulobre-mail-credentials.socket create mode 100644 deploy/systemd/coulobre-mail-credentials@.service create mode 100644 deploy/systemd/coulobre-mail-credentials@.service.d/remote.conf create mode 100644 deploy/systemd/coulobre-mail-credentials@.service.d/rotation.conf create mode 100644 deploy/systemd/coulobre-panel.service.d/credentials-remote-mail.conf create mode 100644 deploy/systemd/coulobre-service-credentials@.service.d/database-rotation.conf create mode 100644 deploy/systemd/coulobre-service-credentials@.service.d/mailbox-rotation.conf diff --git a/deploy/openssh/coulobre-mail-credentials.conf.example b/deploy/openssh/coulobre-mail-credentials.conf.example new file mode 100644 index 0000000..6ab7ef4 --- /dev/null +++ b/deploy/openssh/coulobre-mail-credentials.conf.example @@ -0,0 +1,15 @@ +Match User coulobre-mail-credential-request + AuthenticationMethods publickey + PubkeyAuthentication yes + PasswordAuthentication no + KbdInteractiveAuthentication no + AuthorizedKeysFile /etc/ssh/coulobre-node-keys/%u + AuthorizedKeysCommand none + TrustedUserCAKeys none + DisableForwarding yes + PermitTunnel no + PermitTTY no + PermitUserRC no + ForceCommand /usr/bin/socat -t 92 STDIO UNIX-CONNECT:/run/coulobre-mail-credentials.sock + +Match all diff --git a/deploy/openssh/mail-credential-client.conf.example b/deploy/openssh/mail-credential-client.conf.example new file mode 100644 index 0000000..8482cf2 --- /dev/null +++ b/deploy/openssh/mail-credential-client.conf.example @@ -0,0 +1,13 @@ +Host coulobre-mail-credentials + HostName mail.example.org + Port 22 + User coulobre-mail-credential-request + IdentityFile /etc/coulobre-remote/mail-credentials/id_ed25519 + IdentityAgent none + IdentitiesOnly yes + PreferredAuthentications publickey + UserKnownHostsFile /etc/coulobre-remote/mail-credentials/known_hosts + GlobalKnownHostsFile none + StrictHostKeyChecking yes + BatchMode yes + ConnectTimeout 5 diff --git a/deploy/panel.env.example b/deploy/panel.env.example index 0d04764..a97b656 100644 --- a/deploy/panel.env.example +++ b/deploy/panel.env.example @@ -18,6 +18,10 @@ COULOBRE_BROKER_URL=amqp://coulobre:@127.0.0.1:5672/coulobre # COULOBRE_LOCAL_MAILBOX_PROVISIONING=1 # COULOBRE_LOCAL_DATABASE_CREDENTIALS=1 # COULOBRE_LOCAL_MAILBOX_CREDENTIALS=1 +# COULOBRE_REMOTE_MAILBOX_CREDENTIALS=1 +# COULOBRE_LOCAL_DATABASE_CREDENTIALS_ROTATION=1 +# COULOBRE_LOCAL_MAILBOX_CREDENTIALS_ROTATION=1 +# COULOBRE_REMOTE_MAILBOX_CREDENTIALS_ROTATION=1 # COULOBRE_MAIL_IMAP_HOST=mail.example.org # COULOBRE_PHPMYADMIN_URL=https://tools.example.org/phpmyadmin # COULOBRE_PHPMYADMIN_BRIDGE_KEY= diff --git a/deploy/systemd/coulobre-mail-credentials.socket b/deploy/systemd/coulobre-mail-credentials.socket new file mode 100644 index 0000000..ba1e779 --- /dev/null +++ b/deploy/systemd/coulobre-mail-credentials.socket @@ -0,0 +1,11 @@ +[Unit] +Description=Coulobre mailbox credential socket + +[Socket] +ListenStream=/run/coulobre-mail-credentials.sock +SocketUser=root +SocketGroup=coulobre-credential-requests +SocketMode=0660 +Accept=yes +MaxConnections=4 +RemoveOnStop=true diff --git a/deploy/systemd/coulobre-mail-credentials@.service b/deploy/systemd/coulobre-mail-credentials@.service new file mode 100644 index 0000000..d137167 --- /dev/null +++ b/deploy/systemd/coulobre-mail-credentials@.service @@ -0,0 +1,20 @@ +[Unit] +Description=Coulobre mailbox credential request +After=postfix.service dovecot.service +CollectMode=inactive-or-failed + +[Service] +Type=exec +User=root +WorkingDirectory=/opt/coulobre +UMask=0077 +Environment=COULOBRE_LOCAL_MAILBOX_CREDENTIALS=1 +ExecStart=/opt/coulobre/bin/coulobre-service-credentials --mailbox-only +StandardInput=socket +StandardOutput=socket +StandardError=journal +RuntimeMaxSec=90s +NoNewPrivileges=true +PrivateTmp=true +ProtectHome=true +ProtectSystem=strict diff --git a/deploy/systemd/coulobre-mail-credentials@.service.d/remote.conf b/deploy/systemd/coulobre-mail-credentials@.service.d/remote.conf new file mode 100644 index 0000000..4288c1c --- /dev/null +++ b/deploy/systemd/coulobre-mail-credentials@.service.d/remote.conf @@ -0,0 +1,9 @@ +[Unit] +After=network-online.target +Wants=network-online.target + +[Service] +User=coulobre-mail-credential-relay +ExecStart= +ExecStart=/usr/bin/ssh -T -F /etc/coulobre-remote/mail-credentials/ssh_config coulobre-mail-credentials +RuntimeMaxSec=95s diff --git a/deploy/systemd/coulobre-mail-credentials@.service.d/rotation.conf b/deploy/systemd/coulobre-mail-credentials@.service.d/rotation.conf new file mode 100644 index 0000000..0f9b9d2 --- /dev/null +++ b/deploy/systemd/coulobre-mail-credentials@.service.d/rotation.conf @@ -0,0 +1,4 @@ +[Service] +Environment=COULOBRE_LOCAL_MAILBOX_CREDENTIALS_ROTATION=1 +ReadWritePaths=-/var/lib/coulobre/mail-node /etc/dovecot +RuntimeMaxSec=90s diff --git a/deploy/systemd/coulobre-panel.service.d/credentials-remote-mail.conf b/deploy/systemd/coulobre-panel.service.d/credentials-remote-mail.conf new file mode 100644 index 0000000..e82bc18 --- /dev/null +++ b/deploy/systemd/coulobre-panel.service.d/credentials-remote-mail.conf @@ -0,0 +1,6 @@ +[Unit] +Requires=coulobre-mail-credentials.socket +After=coulobre-mail-credentials.socket + +[Service] +SupplementaryGroups=coulobre-credential-requests diff --git a/deploy/systemd/coulobre-service-credentials@.service.d/database-rotation.conf b/deploy/systemd/coulobre-service-credentials@.service.d/database-rotation.conf new file mode 100644 index 0000000..2a4e375 --- /dev/null +++ b/deploy/systemd/coulobre-service-credentials@.service.d/database-rotation.conf @@ -0,0 +1,4 @@ +[Service] +Environment=COULOBRE_LOCAL_DATABASE_CREDENTIALS_ROTATION=1 +ReadWritePaths=-/var/lib/coulobre/database-node +RuntimeMaxSec=90s diff --git a/deploy/systemd/coulobre-service-credentials@.service.d/mailbox-rotation.conf b/deploy/systemd/coulobre-service-credentials@.service.d/mailbox-rotation.conf new file mode 100644 index 0000000..0f9b9d2 --- /dev/null +++ b/deploy/systemd/coulobre-service-credentials@.service.d/mailbox-rotation.conf @@ -0,0 +1,4 @@ +[Service] +Environment=COULOBRE_LOCAL_MAILBOX_CREDENTIALS_ROTATION=1 +ReadWritePaths=-/var/lib/coulobre/mail-node /etc/dovecot +RuntimeMaxSec=90s diff --git a/docs/deployment.md b/docs/deployment.md index 63a7d20..316a713 100644 --- a/docs/deployment.md +++ b/docs/deployment.md @@ -730,12 +730,45 @@ assigned accounts. Operators need permission to view the account and resource and the relevant **Can reveal database credentials** or **Can reveal mailbox credentials** permission. -Passwords are read directly from the local service and rendered on the -confirmation response. The panel stores access events and outcomes in Django +Passwords are read from the service node and rendered on the confirmation +response. The panel stores access events and outcomes in Django admin under **Service credential accesses**. The audit log includes the actor and resource identifiers. After five incorrect confirmations within five minutes, the panel temporarily stops accepting new attempts for that user. +### Rotate a database or mailbox password + +Enable the corresponding local credential service first. For each local +service that should allow password rotation, install its rotation drop-in +and enable the matching flag in `/etc/coulobre/panel.env`. + +```sh +# COULOBRE_LOCAL_DATABASE_CREDENTIALS_ROTATION=1 +sudo install -D -m 0644 deploy/systemd/coulobre-service-credentials@.service.d/database-rotation.conf \ + /etc/systemd/system/coulobre-service-credentials@.service.d/database-rotation.conf +# COULOBRE_LOCAL_MAILBOX_CREDENTIALS_ROTATION=1 +sudo install -D -m 0644 deploy/systemd/coulobre-service-credentials@.service.d/mailbox-rotation.conf \ + /etc/systemd/system/coulobre-service-credentials@.service.d/mailbox-rotation.conf +sudo systemctl daemon-reload +sudo systemctl restart coulobre-panel +``` + +Open **Connection details**, choose **Rotate password**, and confirm the +current panel password. A customer can rotate a login on their own account. +An operator needs the reveal permission and the corresponding **Can rotate +database credentials** or **Can rotate mailbox credentials** permission. +The service node generates the replacement. Copy it into any application +configuration or mail client using that login before its next connection. +A new phpMyAdmin sign-in reads the current database password. + +If the panel cannot confirm the change, retry from the same form or reopen +it to resume the pending request. MariaDB data and grants, and mailbox +messages and quotas, are retained. Existing sessions can stay connected +until they close. The audit trail records the attempt and outcome. The +password stays in the node's root-only registry and is returned only on an +authorized confirmation. Resolve an unconfirmed rotation before suspending +the account or changing the affected mailbox's quota. + ### Open phpMyAdmin from the panel Enable database credential access first. Install phpMyAdmin with PHP's MySQL @@ -1013,9 +1046,75 @@ corresponding retry action. Check the panel-side relay log with When moving an existing service, migrate its data and provisioning state and let outstanding jobs finish before switching destinations. -For mail on a separate server, retrieve logins on the mail node, and use the +For mail on a separate server, use the [separate-node backup workflow](development.md#bundle-backups-from-separate-nodes). +### Enable connection details for remote mailboxes + +Use a separate SSH identity for credential access. Install the same Coulobre +version on both ends. The key grants access to Coulobre-managed mailbox +logins on that receiver. Keep it with the relay account on the panel and +assign each mailbox domain to one sending installation. + +On the panel node, create the relay user and its SSH directory. Generate a +dedicated key pair, copy the public half to the mail node, and install the +verified SSH host key for the destination as `known_hosts` in the relay +directory. + +```sh +relay=coulobre-mail-credential-relay +dir=/etc/coulobre-remote/mail-credentials +getent group coulobre-credential-requests >/dev/null || sudo groupadd --system coulobre-credential-requests +sudo useradd --system --user-group --no-create-home --home-dir /nonexistent \ + --shell /usr/sbin/nologin "$relay" +sudo install -d -o root -g "$relay" -m 0750 "$dir" +sudo install -o root -g "$relay" -m 0640 deploy/openssh/mail-credential-client.conf.example "$dir/ssh_config" +sudoedit "$dir/ssh_config" +# Install id_ed25519 with owner $relay and mode 0600. +# Install known_hosts with group $relay and mode 0640. +sudo install -m 0644 deploy/systemd/coulobre-mail-credentials.socket \ + deploy/systemd/coulobre-mail-credentials@.service /etc/systemd/system/ +sudo install -D -m 0644 deploy/systemd/coulobre-mail-credentials@.service.d/remote.conf \ + /etc/systemd/system/coulobre-mail-credentials@.service.d/remote.conf +sudo install -D -m 0644 deploy/systemd/coulobre-panel.service.d/credentials-remote-mail.conf \ + /etc/systemd/system/coulobre-panel.service.d/credentials-remote-mail.conf +``` + +On the mail node, save the panel's public key as `mail-credential.pub` and +install the credential receiver and local socket. + +```sh +receiver=coulobre-mail-credential-request +getent group coulobre-credential-requests >/dev/null || sudo groupadd --system coulobre-credential-requests +sudo useradd --system --user-group --groups coulobre-credential-requests \ + --no-create-home --home-dir / --shell /bin/sh "$receiver" +sudo install -d -m 0755 /etc/ssh/coulobre-node-keys +sudo install -m 0644 mail-credential.pub "/etc/ssh/coulobre-node-keys/$receiver" +sudo install -m 0644 deploy/openssh/coulobre-mail-credentials.conf.example \ + /etc/ssh/sshd_config.d/01-coulobre-mail-credentials.conf +sudo install -m 0644 deploy/systemd/coulobre-mail-credentials.socket \ + deploy/systemd/coulobre-mail-credentials@.service /etc/systemd/system/ +sudo sshd -t +sudo systemctl daemon-reload +sudo systemctl reload-or-restart ssh.service +sudo systemctl enable --now coulobre-mail-credentials.socket +``` + +For rotation, also install the receiver's rotation drop-in on the **mail +node** and run `sudo systemctl daemon-reload` there. + +```sh +sudo install -D -m 0644 deploy/systemd/coulobre-mail-credentials@.service.d/rotation.conf \ + /etc/systemd/system/coulobre-mail-credentials@.service.d/rotation.conf +``` + +On the panel, set `COULOBRE_REMOTE_MAILBOX_CREDENTIALS=1` and, for password +changes, `COULOBRE_REMOTE_MAILBOX_CREDENTIALS_ROTATION=1`. Set +`COULOBRE_MAIL_IMAP_HOST` to the mail server's client-facing hostname. Run +`panel_manage migrate --noinput`, reload systemd, and restart +`coulobre-panel`. These flags route mailbox credential requests to the +remote receiver, while databases still use the local credential service. + ## Manage resellers Open **Resellers** to add a reseller login or change an existing reseller's