Confirm and audit credential rotation in the panel

This commit is contained in:
parkel committed 2026-11-21 19:23:01 +01:00
1 parent c2655b57f5
commit 651f041e84
10 files changed
+662 -17

No files matched your search

+157 -4
View File
@@ -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
@@ -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,
),
),
]
+7
View File
@@ -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"),
]
+13
View File
@@ -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
+5
View File
@@ -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(
+156 -8
View File
@@ -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"])
@@ -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 %}
<a class="back-link" href="{{ account.get_absolute_url }}">← {{ account.name }}</a>
<header class="page-heading">
<div>
<h1>Connection details</h1>
<h1>{% if rotating %}Rotate password{% else %}Connection details{% endif %}</h1>
<p class="heading-meta domain">{{ resource }}</p>
</div>
</header>
<section class="surface editor-surface">
{% if fields %}
{% if rotation_problem %}
<p role="alert">{{ rotation_problem }}</p>
<a class="button secondary" href="{{ account.get_absolute_url }}">Back to hosting account</a>
{% elif fields %}
<div class="editor">
{% if rotating %}
{% if database %}<p>Password changed. Update the database password in each application that uses this login.</p>
{% else %}<p>Password changed. Update the saved login in your mail clients.</p>{% endif %}
{% endif %}
{% for key, label, value in fields %}
<div>
<label for="credential-{{ key }}">{{ label }}</label>
@@ -24,16 +31,24 @@
<p aria-live="polite" id="credential-copy-status"></p>
<div class="form-actions">
<a class="button secondary" href="{{ account.get_absolute_url }}">Done</a>
{% if rotation_url %}<a class="button secondary" href="{{ rotation_url }}">Rotate password</a>{% endif %}
</div>
</div>
<script src="{% static 'hosting/credential-copy.js' %}" defer></script>
{% else %}
<form method="post" class="editor">
<p>Confirm your current panel password to show the service login.</p>
{% if rotating %}
<p>Confirm your panel password to generate a replacement password for this login.</p>
{% if database %}<p>Applications using the previous password will need the new one when they reconnect.</p>
{% else %}<p>Mail clients using the previous password will need the new one when they reconnect.</p>{% endif %}
{% else %}
<p>Confirm your current panel password to show the service login.</p>
{% endif %}
{% csrf_token %}
{{ form.as_div }}
<div class="form-actions">
<button class="button primary" type="submit">Show connection details</button>
<button class="button primary" type="submit">{% if rotating %}Rotate password{% else %}Show connection details{% endif %}</button>
{% if rotation_url %}<a class="button secondary" href="{{ rotation_url }}">Rotate password</a>{% endif %}
<a class="button secondary" href="{{ account.get_absolute_url }}">Cancel</a>
</div>
</form>
@@ -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)
+10
View File
@@ -163,6 +163,11 @@ urlpatterns = [
DatabaseCredentialView.as_view(),
name="database_credentials",
),
path(
"databases/<int:pk>/credentials/rotate/",
DatabaseCredentialView.as_view(rotating=True),
name="database_credential_rotation",
),
path(
"databases/<int:pk>/manifest/",
views.DownloadDatabaseManifest.as_view(),
@@ -203,6 +208,11 @@ urlpatterns = [
MailboxCredentialView.as_view(),
name="mailbox_credentials",
),
path(
"mailboxes/<int:pk>/credentials/rotate/",
MailboxCredentialView.as_view(rotating=True),
name="mailbox_credential_rotation",
),
path(
"mailboxes/<int:pk>/manifest/",
views.DownloadMailboxManifest.as_view(),
+12
View File
@@ -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"
)