Files
coulobre/src/coulobre/hosting/service_credentials.py
T
parkel 9fb42d9625
Coulobre Panel CI / Checks (Python 3.12) (pull_request) Successful in 2m0s
Coulobre Panel CI / Checks (Python 3.14) (pull_request) Successful in 2m14s
Allow operators to manage hosting as a customer
2026-12-04 15:13:59 +01:00

323 lines
10 KiB
Python

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 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.database_login import DatabaseLoginSpec
from coulobre.service_credentials import (
CREDENTIAL_SOCKET,
CREDENTIAL_TIMEOUT_SECONDS,
CREDENTIALS_UNAVAILABLE,
MAIL_CREDENTIAL_SOCKET,
MAIL_PASSWORD_SOCKET,
ROTATION_TIMEOUT_SECONDS,
ServiceCredentialRequest,
)
from .access import customer_for_user, reseller_for_user
from .installation_features import panel_feature_allowed
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: (
"hosting.view_hostingaccount",
"hosting.view_hostingdatabase",
"hosting.reveal_database_credentials",
),
CredentialKind.MAILBOX: (
"hosting.view_hostingaccount",
"hosting.view_hostingmailbox",
"hosting.reveal_mailbox_credentials",
),
}
ROTATION_PERMISSIONS = {
CredentialKind.DATABASE: "hosting.rotate_database_credentials",
CredentialKind.MAILBOX: "hosting.rotate_mailbox_credentials",
}
class ConfirmCredentialAccessForm(forms.Form):
password = forms.CharField(
label="Panel password",
strip=False,
max_length=4096,
widget=forms.PasswordInput(attrs={"autocomplete": "current-password"}),
)
def enabled_credential_access(request, kind):
if settings.DEBUG or not request.is_secure():
return False
if kind == CredentialKind.DATABASE:
return settings.LOCAL_DATABASE_CREDENTIALS
return (
settings.REMOTE_MAILBOX_CREDENTIALS
or settings.LOCAL_MAILBOX_CREDENTIALS
)
def enabled_rotation(request, kind):
if kind == CredentialKind.MAILBOX and mailbox_password_changes_enabled():
return not settings.DEBUG and request.is_secure()
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 mailbox_password_changes_enabled():
return panel_feature_allowed(
"MAILBOX_PASSWORD_CHANGES"
) and panel_feature_allowed("LOCAL_MAILBOX_PROVISIONING")
def can_reveal_credentials(user, kind):
if not user.is_authenticated or not user.is_active:
return False
if customer_for_user(user) is not None:
return True
if reseller_for_user(user) is not None:
return False
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])
)
def show_credential_action(request, kind):
return (
getattr(request, "impersonation", None) is None
and enabled_credential_access(request, kind)
and can_reveal_credentials(request.user, kind)
)
def credential_actor(request):
return getattr(request, "support_operator", request.user)
def show_rotation_action(request, kind):
session = getattr(request, "impersonation", None)
if session is not None and not (
session.managed_enabled
and credential_actor(request).has_perms(CREDENTIAL_PERMISSIONS[kind])
and credential_actor(request).has_perm(ROTATION_PERMISSIONS[kind])
):
return False
return enabled_rotation(request, kind) and can_rotate_credentials(
request.user, kind
)
@transaction.atomic
@sensitive_variables()
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.
users.update(last_login=F("last_login"))
actor = users.select_for_update().first()
if actor is None:
raise PermissionDenied
now = timezone.now()
recent_failures = ServiceCredentialAccess.objects.filter(
actor=actor,
outcome=CredentialOutcome.REJECTED,
requested_at__gt=now - ATTEMPT_WINDOW,
).count()
if recent_failures >= ATTEMPT_LIMIT:
return None
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,
resource=resource,
requested_at=now,
outcome=CredentialOutcome.REQUESTED
if accepted
else CredentialOutcome.REJECTED,
)
@sensitive_variables()
def send_credential_request(spec):
address = CREDENTIAL_SOCKET
timeout = (
ROTATION_TIMEOUT_SECONDS
if spec.operation == "rotate"
else CREDENTIAL_TIMEOUT_SECONDS
)
if spec.kind == CredentialKind.MAILBOX:
if spec.operation != "read" and mailbox_password_changes_enabled():
address = MAIL_PASSWORD_SOCKET
timeout = 50
elif settings.REMOTE_MAILBOX_CREDENTIALS:
address = MAIL_CREDENTIAL_SOCKET
return apply_on_local_node(
spec,
address,
"credential node",
"service credential request",
timeout=timeout,
)
@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")
expected = {
"database": (
resource.database.name
if isinstance(resource, DatabaseLoginSpec)
else resource.name
),
"user": resource.name,
"host": "localhost",
}
else:
expected = {"user": resource.address}
if any(
not isinstance(reply.get(key), str)
or not reply[key].isprintable()
or len(reply[key]) > 512
for key in keys
) 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"])