diff --git a/deploy/panel.env.example b/deploy/panel.env.example index a97b656..37a8468 100644 --- a/deploy/panel.env.example +++ b/deploy/panel.env.example @@ -25,6 +25,8 @@ COULOBRE_BROKER_URL=amqp://coulobre:@127.0.0.1:5672/coulobre # COULOBRE_MAIL_IMAP_HOST=mail.example.org # COULOBRE_PHPMYADMIN_URL=https://tools.example.org/phpmyadmin # COULOBRE_PHPMYADMIN_BRIDGE_KEY= +# COULOBRE_ROUNDCUBE_URL=https://webmail.example.org +# COULOBRE_ROUNDCUBE_BRIDGE_KEY= # COULOBRE_LOCAL_ACCOUNT_BACKUPS=1 # COULOBRE_LOCAL_ACCOUNT_BACKUP_MAIL=1 # COULOBRE_LOCAL_BACKUP_RETENTION=1 diff --git a/src/coulobre/hosting/migrations/0038_roundcube_signon.py b/src/coulobre/hosting/migrations/0038_roundcube_signon.py new file mode 100644 index 0000000..4ce3420 --- /dev/null +++ b/src/coulobre/hosting/migrations/0038_roundcube_signon.py @@ -0,0 +1,60 @@ +# Generated by Django 5.2.19 on 2026-11-21 19:08 + +import django.db.models.deletion +from django.conf import settings +from django.db import migrations, models + + +class Migration(migrations.Migration): + dependencies = [ + ("hosting", "0037_account_retirement"), + migrations.swappable_dependency(settings.AUTH_USER_MODEL), + ] + + operations = [ + migrations.AlterField( + model_name="servicecredentialaccess", + name="method", + field=models.CharField( + choices=[ + ("reveal", "Show connection details"), + ("phpmyadmin", "phpMyAdmin"), + ("webmail", "Roundcube"), + ("rotate", "Rotate password"), + ], + default="reveal", + max_length=10, + ), + ), + migrations.CreateModel( + name="RoundcubeGrant", + fields=[ + ( + "token_digest", + models.CharField( + max_length=64, primary_key=True, serialize=False + ), + ), + ("expires_at", models.DateTimeField(db_index=True)), + ("redeemed_at", models.DateTimeField(blank=True, null=True)), + ("address", models.CharField(max_length=254)), + ( + "actor", + models.ForeignKey( + on_delete=django.db.models.deletion.CASCADE, + to=settings.AUTH_USER_MODEL, + ), + ), + ( + "mailbox", + models.ForeignKey( + on_delete=django.db.models.deletion.CASCADE, + to="hosting.hostingmailbox", + ), + ), + ], + options={ + "abstract": False, + }, + ), + ] diff --git a/src/coulobre/hosting/models.py b/src/coulobre/hosting/models.py index 746f47d..0557c5b 100644 --- a/src/coulobre/hosting/models.py +++ b/src/coulobre/hosting/models.py @@ -171,6 +171,7 @@ class ServiceCredentialAccess(models.Model): class Method(models.TextChoices): REVEAL = "reveal", "Show connection details" PHPMYADMIN = "phpmyadmin", "phpMyAdmin" + WEBMAIL = "webmail", "Roundcube" ROTATE = "rotate", "Rotate password" method = models.CharField( @@ -441,15 +442,26 @@ class HostingDatabase(models.Model): return DatabaseSpec(self.account_id, self.suffix) -class PhpMyAdminGrant(models.Model): +class ServiceSignOnGrant(models.Model): token_digest = models.CharField(max_length=64, primary_key=True) actor = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE ) - database = models.ForeignKey(HostingDatabase, on_delete=models.CASCADE) expires_at = models.DateTimeField(db_index=True) redeemed_at = models.DateTimeField(null=True, blank=True) + class Meta: + abstract = True + + +class PhpMyAdminGrant(ServiceSignOnGrant): + database = models.ForeignKey(HostingDatabase, on_delete=models.CASCADE) + + +class RoundcubeGrant(ServiceSignOnGrant): + mailbox = models.ForeignKey("HostingMailbox", on_delete=models.CASCADE) + address = models.CharField(max_length=254) + class DirectAdminImport(models.Model): account = models.OneToOneField( diff --git a/src/coulobre/hosting/phpmyadmin.py b/src/coulobre/hosting/phpmyadmin.py index 3b1530d..ea5c766 100644 --- a/src/coulobre/hosting/phpmyadmin.py +++ b/src/coulobre/hosting/phpmyadmin.py @@ -1,14 +1,6 @@ -import hashlib -import hmac -import re -import secrets -from datetime import timedelta - from django.conf import settings -from django.db import transaction from django.http import Http404, JsonResponse from django.shortcuts import render -from django.utils import timezone from django.views.decorators.cache import never_cache from django.views.decorators.csrf import csrf_exempt from django.views.decorators.debug import ( @@ -27,9 +19,7 @@ from .service_credentials import ( enabled_credential_access, fetch_service_credentials, ) - -GRANT_LIFETIME = timedelta(seconds=45) -TOKEN_PATTERN = re.compile(r"[A-Za-z0-9_-]{43}") +from .signon import bridge_ticket, consume_signon_grant, issue_signon_grant def phpmyadmin_available(request): @@ -52,52 +42,24 @@ class PhpMyAdminLaunch(DatabaseCredentialView): def post(self, request, *args, **kwargs): if not phpmyadmin_available(request): raise Http404 - token = issue_database_grant(request.user, self.resource) + token = issue_signon_grant( + PhpMyAdminGrant, request.user, database=self.resource + ) return render( request, - "hosting/phpmyadmin_launch.html", + "hosting/service_signon.html", { "destination": settings.PHPMYADMIN_URL + "/coulobre-signon.php", "ticket": token, - "database": self.resource.spec.name, + "product": "phpMyAdmin", + "resource": self.resource.spec.name, + "ticket_field": "ticket", "account": self.account, }, ) -@sensitive_variables() -def issue_database_grant(actor, database): - now = timezone.now() - PhpMyAdminGrant.objects.filter(expires_at__lte=now).delete() - token = secrets.token_urlsafe(32) - PhpMyAdminGrant.objects.create( - token_digest=token_digest(token), - actor=actor, - database=database, - expires_at=now + GRANT_LIFETIME, - ) - return token - - -@sensitive_variables() -def token_digest(token): - return hashlib.sha256(token.encode("ascii")).hexdigest() - - -@transaction.atomic -@sensitive_variables() -def consume_database_grant(token): - now = timezone.now() - digest = token_digest(token) - current = PhpMyAdminGrant.objects.filter(pk=digest) - if not current.filter(expires_at__gt=now, redeemed_at__isnull=True).update( - redeemed_at=now - ): - return None - return current.select_related("actor", "database__account").first() - - def actor_has_database_access(actor, database): if database.account.retired_at is not None or not can_reveal_credentials( actor, CredentialKind.DATABASE @@ -115,16 +77,8 @@ def actor_has_database_access(actor, database): def redeem_phpmyadmin(request): if not phpmyadmin_available(request): raise Http404 - key = request.headers.get("X-Coulobre-Bridge-Key", "") - if not hmac.compare_digest( - key.encode("utf-8"), settings.PHPMYADMIN_BRIDGE_KEY.encode("utf-8") - ): - raise Http404 - token = request.POST.get("ticket", "") - if not TOKEN_PATTERN.fullmatch(token): - raise Http404 - - grant = consume_database_grant(token) + token = bridge_ticket(request, settings.PHPMYADMIN_BRIDGE_KEY) + grant = consume_signon_grant(PhpMyAdminGrant, token, "database__account") if grant is None or not actor_has_database_access( grant.actor, grant.database ): diff --git a/src/coulobre/hosting/roundcube.py b/src/coulobre/hosting/roundcube.py new file mode 100644 index 0000000..8c3ce1d --- /dev/null +++ b/src/coulobre/hosting/roundcube.py @@ -0,0 +1,156 @@ +from django.conf import settings +from django.contrib.auth import get_user_model +from django.http import Http404, JsonResponse +from django.shortcuts import render +from django.views.decorators.cache import never_cache +from django.views.decorators.csrf import csrf_exempt +from django.views.decorators.debug import ( + sensitive_post_parameters, + sensitive_variables, +) +from django.views.decorators.http import require_POST + +from .access import customer_for_user +from .credential_views import MailboxCredentialView +from .models import HostingMailbox, RoundcubeGrant, ServiceCredentialAccess +from .service_credentials import ( + CredentialKind, + CredentialOutcome, + can_reveal_credentials, + enabled_credential_access, + fetch_service_credentials, +) +from .signon import bridge_ticket, consume_signon_grant, issue_signon_grant + + +def roundcube_available(request): + return bool( + settings.ROUNDCUBE_URL + and settings.ROUNDCUBE_BRIDGE_KEY + and enabled_credential_access(request, CredentialKind.MAILBOX) + ) + + +def mailbox_can_open_webmail(mailbox): + account = mailbox.mail_domain.account + job = getattr(mailbox, "provisioning", None) + return ( + not account.services_suspended + and account.retired_at is None + and (job is None or job.state == "configured") + ) + + +def actor_can_open_webmail(actor, mailbox): + if not ( + can_reveal_credentials(actor, CredentialKind.MAILBOX) + and mailbox_can_open_webmail(mailbox) + ): + return False + customer = customer_for_user(actor) + return ( + customer is None + or mailbox.mail_domain.account.customer_id == customer.pk + ) + + +class RoundcubeLaunch(MailboxCredentialView): + http_method_names = ["post"] + + def dispatch(self, request, *args, **kwargs): + response = super().dispatch(request, *args, **kwargs) + response["Referrer-Policy"] = "origin" + return response + + @sensitive_variables() + def post(self, request, *args, **kwargs): + if not roundcube_available(request): + raise Http404 + mailbox = self.resource + if not actor_can_open_webmail(request.user, mailbox): + raise Http404 + token = issue_signon_grant( + RoundcubeGrant, + request.user, + mailbox=mailbox, + address=mailbox.spec.address, + ) + return render( + request, + "hosting/service_signon.html", + { + "destination": settings.ROUNDCUBE_URL + "/", + "product": "Roundcube", + "resource": mailbox.spec.address, + "ticket_field": "_coulobre_ticket", + "ticket": token, + "account": self.account, + }, + ) + + +@csrf_exempt +@require_POST +@never_cache +@sensitive_post_parameters("ticket") +@sensitive_variables() +def redeem_roundcube(request): + if not roundcube_available(request): + raise Http404 + + token = bridge_ticket(request, settings.ROUNDCUBE_BRIDGE_KEY) + grant = consume_signon_grant( + RoundcubeGrant, + token, + "mailbox__mail_domain__account", + "mailbox__provisioning", + ) + if grant is None or not actor_can_open_webmail(grant.actor, grant.mailbox): + raise Http404 + mailbox = grant.mailbox + spec = mailbox.spec + if grant.address != spec.address: + raise Http404 + + audit = ServiceCredentialAccess.objects.create( + actor=grant.actor, + actor_username=grant.actor.get_username(), + hosting_account_id=mailbox.mail_domain.account_id, + kind=CredentialKind.MAILBOX, + resource=spec.address, + method=ServiceCredentialAccess.Method.WEBMAIL, + outcome=CredentialOutcome.REQUESTED, + ) + try: + credentials = fetch_service_credentials(spec) + except (OSError, ValueError): + record_outcome(audit, CredentialOutcome.UNAVAILABLE) + return JsonResponse( + {"error": "Mailbox login unavailable."}, status=503 + ) + + current = ( + HostingMailbox.objects.select_related( + "mail_domain__account", "provisioning" + ) + .filter(pk=mailbox.pk) + .first() + ) + actor = get_user_model().objects.filter(pk=grant.actor_id).first() + if ( + current is None + or actor is None + or current.spec != spec + or not actor_can_open_webmail(actor, current) + ): + record_outcome(audit, CredentialOutcome.UNAVAILABLE) + raise Http404 + record_outcome(audit, CredentialOutcome.REVEALED) + response = JsonResponse(credentials) + response["Referrer-Policy"] = "no-referrer" + return response + + +def record_outcome(audit, outcome): + audit.outcome = outcome + audit.save(update_fields=["outcome"]) diff --git a/src/coulobre/hosting/signon.py b/src/coulobre/hosting/signon.py new file mode 100644 index 0000000..af7a0ef --- /dev/null +++ b/src/coulobre/hosting/signon.py @@ -0,0 +1,57 @@ +import hashlib +import hmac +import re +import secrets +from datetime import timedelta + +from django.db import transaction +from django.http import Http404 +from django.utils import timezone +from django.views.decorators.debug import sensitive_variables + +GRANT_LIFETIME = timedelta(seconds=45) +TOKEN_PATTERN = re.compile(r"[A-Za-z0-9_-]{43}") + + +@sensitive_variables() +def issue_signon_grant(model, actor, **selection): + now = timezone.now() + model.objects.filter(expires_at__lte=now).delete() + token = secrets.token_urlsafe(32) + model.objects.create( + token_digest=token_digest(token), + actor=actor, + expires_at=now + GRANT_LIFETIME, + **selection, + ) + return token + + +@sensitive_variables() +def token_digest(token): + return hashlib.sha256(token.encode("ascii")).hexdigest() + + +@transaction.atomic +@sensitive_variables() +def consume_signon_grant(model, token, *related): + now = timezone.now() + current = model.objects.filter(pk=token_digest(token)) + if not current.filter(expires_at__gt=now, redeemed_at__isnull=True).update( + redeemed_at=now + ): + return None + return current.select_related("actor", *related).first() + + +@sensitive_variables() +def bridge_ticket(request, expected_key): + key = request.headers.get("X-Coulobre-Bridge-Key", "") + if not expected_key or not hmac.compare_digest( + key.encode("utf-8"), expected_key.encode("utf-8") + ): + raise Http404 + ticket = request.POST.get("ticket", "") + if not TOKEN_PATTERN.fullmatch(ticket): + raise Http404 + return ticket diff --git a/src/coulobre/hosting/static/hosting/phpmyadmin-launch.js b/src/coulobre/hosting/static/hosting/phpmyadmin-launch.js deleted file mode 100644 index 77d59dd..0000000 --- a/src/coulobre/hosting/static/hosting/phpmyadmin-launch.js +++ /dev/null @@ -1,3 +0,0 @@ -"use strict"; - -document.getElementById("phpmyadmin-launch").submit(); diff --git a/src/coulobre/hosting/static/hosting/service-signon.js b/src/coulobre/hosting/static/hosting/service-signon.js new file mode 100644 index 0000000..f8588c9 --- /dev/null +++ b/src/coulobre/hosting/static/hosting/service-signon.js @@ -0,0 +1,3 @@ +"use strict"; + +document.getElementById("service-signon").submit(); diff --git a/src/coulobre/hosting/templates/hosting/account_detail.html b/src/coulobre/hosting/templates/hosting/account_detail.html index b2c252f..19f47a4 100644 --- a/src/coulobre/hosting/templates/hosting/account_detail.html +++ b/src/coulobre/hosting/templates/hosting/account_detail.html @@ -209,6 +209,12 @@