+ {% 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 @@
{% else %}
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/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/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/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}
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"
)