From 07b26838c9d02b6cce50337f3c362e3006f9989b Mon Sep 17 00:00:00 2001 From: Peter van Arkel Date: Sat, 21 Nov 2026 20:18:05 +0100 Subject: [PATCH] Add mailbox-scoped sign-on for Roundcube --- deploy/panel.env.example | 2 + .../migrations/0038_roundcube_signon.py | 60 ++++++ src/coulobre/hosting/models.py | 16 +- src/coulobre/hosting/phpmyadmin.py | 66 +----- src/coulobre/hosting/roundcube.py | 156 ++++++++++++++ src/coulobre/hosting/signon.py | 57 +++++ .../static/hosting/phpmyadmin-launch.js | 3 - .../hosting/static/hosting/service-signon.js | 3 + .../templates/hosting/account_detail.html | 6 + .../templates/hosting/phpmyadmin_launch.html | 21 -- .../templates/hosting/service_signon.html | 21 ++ src/coulobre/hosting/test_roundcube.py | 200 ++++++++++++++++++ src/coulobre/hosting/urls.py | 7 + src/coulobre/hosting/views.py | 15 ++ src/coulobre/settings.py | 22 ++ 15 files changed, 573 insertions(+), 82 deletions(-) create mode 100644 src/coulobre/hosting/migrations/0038_roundcube_signon.py create mode 100644 src/coulobre/hosting/roundcube.py create mode 100644 src/coulobre/hosting/signon.py delete mode 100644 src/coulobre/hosting/static/hosting/phpmyadmin-launch.js create mode 100644 src/coulobre/hosting/static/hosting/service-signon.js delete mode 100644 src/coulobre/hosting/templates/hosting/phpmyadmin_launch.html create mode 100644 src/coulobre/hosting/templates/hosting/service_signon.html create mode 100644 src/coulobre/hosting/test_roundcube.py 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 @@ {{ mailbox }} + {% if mailbox.pk in webmail_mailbox_ids %} +
+ {% csrf_token %} + +
+ {% endif %} {% if show_mailbox_credentials %}
Connection details
{% endif %} diff --git a/src/coulobre/hosting/templates/hosting/phpmyadmin_launch.html b/src/coulobre/hosting/templates/hosting/phpmyadmin_launch.html deleted file mode 100644 index 2833665..0000000 --- a/src/coulobre/hosting/templates/hosting/phpmyadmin_launch.html +++ /dev/null @@ -1,21 +0,0 @@ -{% extends "hosting/base.html" %} -{% load static %} -{% block title %}Opening phpMyAdmin · Coulobre Panel{% endblock %} -{% block content %} - ← {{ account.name }} -
-
-

Opening phpMyAdmin

-

{{ database }}

-
-
-
-
- -
- -
-
-
- -{% endblock %} diff --git a/src/coulobre/hosting/templates/hosting/service_signon.html b/src/coulobre/hosting/templates/hosting/service_signon.html new file mode 100644 index 0000000..4f3cacd --- /dev/null +++ b/src/coulobre/hosting/templates/hosting/service_signon.html @@ -0,0 +1,21 @@ +{% extends "hosting/base.html" %} +{% load static %} +{% block title %}Opening {{ product }} · Coulobre Panel{% endblock %} +{% block content %} + ← {{ account.name }} +
+
+

Opening {{ product }}

+

{{ resource }}

+
+
+
+
+ +
+ +
+
+
+ +{% endblock %} diff --git a/src/coulobre/hosting/test_roundcube.py b/src/coulobre/hosting/test_roundcube.py new file mode 100644 index 0000000..3f33526 --- /dev/null +++ b/src/coulobre/hosting/test_roundcube.py @@ -0,0 +1,200 @@ +import re +from unittest.mock import patch + +from django.contrib.auth import get_user_model +from django.test import Client, TestCase, override_settings +from django.urls import reverse +from django.utils import timezone + +from .models import ( + Customer, + HostingAccount, + HostingMailbox, + HostingMailDomain, + MailboxProvisioning, + PhpMyAdminGrant, + RoundcubeGrant, + ServiceCredentialAccess, +) +from .signon import issue_signon_grant + +BRIDGE_KEY = "roundcube-fixture-bridge-key-with-separate-access" +MAIL_PASSWORD = "fixture-mailbox-password" + + +@override_settings( + DEBUG=False, + LOCAL_MAILBOX_CREDENTIALS=False, + REMOTE_MAILBOX_CREDENTIALS=True, + ROUNDCUBE_URL="https://webmail.example.org", + ROUNDCUBE_BRIDGE_KEY=BRIDGE_KEY, +) +class RoundcubeSignOnTests(TestCase): + @classmethod + def setUpTestData(cls): + users = get_user_model().objects + cls.user = users.create_user("tenant") + cls.other = users.create_user("other") + cls.customer = Customer.objects.create(user=cls.user) + cls.other_customer = Customer.objects.create(user=cls.other) + cls.account = HostingAccount.objects.create( + name="Own site", + primary_domain="site.example", + customer=cls.customer, + ) + domain = HostingMailDomain.objects.create( + account=cls.account, domain=cls.account.primary_domain + ) + cls.first = HostingMailbox.objects.create( + mail_domain=domain, local_part="first", quota_mib=10 + ) + cls.second = HostingMailbox.objects.create( + mail_domain=domain, local_part="second" + ) + + def setUp(self): + self.client.force_login(self.user) + self.bridge = reverse("panel:roundcube_redeem") + + def launch_url(self, mailbox): + return reverse("panel:roundcube_launch", args=[mailbox.pk]) + + def issue(self, mailbox): + response = self.client.post(self.launch_url(mailbox), secure=True) + self.assertContains(response, mailbox.spec.address) + self.assertContains(response, 'action="https://webmail.example.org/"') + self.assertNotContains(response, MAIL_PASSWORD) + self.assertIn("no-store", response.headers["Cache-Control"]) + self.assertEqual(response.headers["Referrer-Policy"], "origin") + ticket = ( + re.search( + rb'name="_coulobre_ticket" value="([A-Za-z0-9_-]{43})"', + response.content, + ) + .group(1) + .decode("ascii") + ) + return ticket + + def redeem(self, ticket, key=BRIDGE_KEY): + return Client().post( + self.bridge, + {"ticket": ticket}, + secure=True, + headers={"X-Coulobre-Bridge-Key": key}, + ) + + def test_each_launch_redeems_only_its_selected_mailbox(self): + index = self.client.get(self.account.get_absolute_url(), secure=True) + self.assertContains(index, ">Open webmail", count=2) + first, second = self.issue(self.first), self.issue(self.second) + self.assertFalse( + RoundcubeGrant.objects.filter( + token_digest__in=[first, second] + ).exists() + ) + with patch( + "coulobre.hosting.roundcube.fetch_service_credentials", + side_effect=lambda spec: { + "user": spec.address, + "password": MAIL_PASSWORD, + }, + ) as node: + for ticket, mailbox in ( + (first, self.first), + (second, self.second), + ): + response = self.redeem(ticket) + self.assertEqual(response.status_code, 200) + self.assertEqual( + response.json(), + {"user": mailbox.spec.address, "password": MAIL_PASSWORD}, + ) + self.assertIn("no-store", response.headers["Cache-Control"]) + self.assertEqual(self.redeem(ticket).status_code, 404) + self.assertEqual( + [call.args[0] for call in node.call_args_list], + [self.first.spec, self.second.spec], + ) + audits = ServiceCredentialAccess.objects.filter(method="webmail") + self.assertEqual( + set(audits.values_list("resource", flat=True)), + {self.first.spec.address, self.second.spec.address}, + ) + self.assertNotIn(MAIL_PASSWORD, str(list(audits.values()))) + + def test_expiry_key_and_product_boundaries(self): + ticket = self.issue(self.first) + self.assertEqual(self.redeem(ticket, "wrong key").status_code, 404) + self.assertIsNone(RoundcubeGrant.objects.get().redeemed_at) + RoundcubeGrant.objects.update(expires_at=timezone.now()) + self.assertEqual(self.redeem(ticket).status_code, 404) + database = self.account.databases.create(suffix="app") + database_ticket = issue_signon_grant( + PhpMyAdminGrant, self.user, database=database + ) + self.assertEqual(self.redeem(database_ticket).status_code, 404) + self.assertIsNone(PhpMyAdminGrant.objects.get().redeemed_at) + + def test_another_tenant_cannot_launch_and_old_grants_lose_access(self): + ticket = self.issue(self.first) + self.client.force_login(self.other) + self.assertEqual( + self.client.post( + self.launch_url(self.first), secure=True + ).status_code, + 404, + ) + HostingAccount.objects.filter(pk=self.account.pk).update( + customer=self.other_customer + ) + with patch( + "coulobre.hosting.roundcube.fetch_service_credentials" + ) as node: + self.assertEqual(self.redeem(ticket).status_code, 404) + node.assert_not_called() + + def test_suspension_blocks_an_issued_ticket(self): + ticket = self.issue(self.first) + HostingAccount.objects.filter(pk=self.account.pk).update( + services_suspended=True + ) + self.assertNotContains( + self.client.get(self.account.get_absolute_url(), secure=True), + "Open webmail", + ) + self.assertEqual(self.redeem(ticket).status_code, 404) + + def test_an_unfinished_mailbox_request_cannot_launch(self): + MailboxProvisioning.objects.create(mailbox=self.first) + response = self.client.get( + self.account.get_absolute_url(), secure=True + ) + self.assertContains(response, ">Open webmail", count=1) + self.assertEqual( + self.client.post( + self.launch_url(self.first), secure=True + ).status_code, + 404, + ) + + def test_requires_post_and_csrf(self): + url = self.launch_url(self.first) + self.assertEqual(self.client.get(url, secure=True).status_code, 405) + client = Client(enforce_csrf_checks=True) + client.force_login(self.user) + self.assertEqual(client.post(url, secure=True).status_code, 403) + self.assertFalse(RoundcubeGrant.objects.exists()) + + @override_settings(ROUNDCUBE_URL="") + def test_opt_in_is_required(self): + self.assertNotContains( + self.client.get(self.account.get_absolute_url(), secure=True), + "Open webmail", + ) + self.assertEqual( + self.client.post( + self.launch_url(self.first), secure=True + ).status_code, + 404, + ) diff --git a/src/coulobre/hosting/urls.py b/src/coulobre/hosting/urls.py index 0650aff..e508d9b 100644 --- a/src/coulobre/hosting/urls.py +++ b/src/coulobre/hosting/urls.py @@ -13,6 +13,7 @@ from .reseller_views import ( ResellerList, ) from .retirement_views import RetirementList, RetirementView +from .roundcube import RoundcubeLaunch, redeem_roundcube app_name = "panel" @@ -165,6 +166,12 @@ urlpatterns = [ name="phpmyadmin_launch", ), path("_bridge/phpmyadmin/", redeem_phpmyadmin, name="phpmyadmin_redeem"), + path( + "mailboxes//webmail/", + RoundcubeLaunch.as_view(), + name="roundcube_launch", + ), + path("_bridge/roundcube/", redeem_roundcube, name="roundcube_redeem"), path( "databases//credentials/", DatabaseCredentialView.as_view(), diff --git a/src/coulobre/hosting/views.py b/src/coulobre/hosting/views.py index d6a70a0..1888ae2 100644 --- a/src/coulobre/hosting/views.py +++ b/src/coulobre/hosting/views.py @@ -110,6 +110,7 @@ from .resource_requests import ( require_open_account, ) from .retirement_views import RETIRE_ACCOUNTS +from .roundcube import mailbox_can_open_webmail, roundcube_available from .service_changes import request_service_change from .service_credentials import ( CredentialKind, @@ -490,6 +491,9 @@ class AccountDetail(TenantScopeMixin, PermissionRequiredMixin, DetailView): context["show_phpmyadmin"] = context[ "show_database_credentials" ] and phpmyadmin_available(self.request) + context["show_webmail"] = context[ + "show_mailbox_credentials" + ] and roundcube_available(self.request) if tenant or user.has_perm(VIEW_DATABASES): databases = self.object.databases.all() if not tenant and user.has_perms(PROVISION_DATABASE): @@ -525,6 +529,17 @@ class AccountDetail(TenantScopeMixin, PermissionRequiredMixin, DetailView): context["change_mailbox_quota"] = user.has_perms( CHANGE_MAILBOX_QUOTA ) + if context.get("show_webmail"): + mailboxes = list( + mailboxes.select_related( + "mail_domain__account", "provisioning" + ) + ) + context["webmail_mailbox_ids"] = { + mailbox.pk + for mailbox in mailboxes + if mailbox_can_open_webmail(mailbox) + } context["mailboxes"] = mailboxes return context diff --git a/src/coulobre/settings.py b/src/coulobre/settings.py index f96d455..7ad32c6 100644 --- a/src/coulobre/settings.py +++ b/src/coulobre/settings.py @@ -1,4 +1,5 @@ import os +import re from pathlib import Path from urllib.parse import urlsplit @@ -175,6 +176,27 @@ if PHPMYADMIN_URL: "Set a random phpMyAdmin bridge key of at least 32 characters." ) +ROUNDCUBE_URL = os.environ.get("COULOBRE_ROUNDCUBE_URL", "").rstrip("/") +ROUNDCUBE_BRIDGE_KEY = os.environ.get("COULOBRE_ROUNDCUBE_BRIDGE_KEY", "") +if ROUNDCUBE_URL: + roundcube = urlsplit(ROUNDCUBE_URL) + if ( + roundcube.scheme != "https" + or not roundcube.hostname + or roundcube.username is not None + or roundcube.query + or roundcube.fragment + or any(character.isspace() for character in ROUNDCUBE_URL) + ): + raise ImproperlyConfigured("Set an HTTPS Roundcube base URL.") + if ( + re.fullmatch(r"[A-Za-z0-9_-]{32,128}", ROUNDCUBE_BRIDGE_KEY) is None + or ROUNDCUBE_BRIDGE_KEY == PHPMYADMIN_BRIDGE_KEY + ): + raise ImproperlyConfigured( + "Set a dedicated random Roundcube bridge key." + ) + LOCAL_ACCOUNT_BACKUPS = os.environ.get("COULOBRE_LOCAL_ACCOUNT_BACKUPS") == "1" LOCAL_ACCOUNT_BACKUP_MAIL = ( os.environ.get("COULOBRE_LOCAL_ACCOUNT_BACKUP_MAIL") == "1"