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/deploy/roundcube/apache.conf.example b/deploy/roundcube/apache.conf.example
new file mode 100644
index 0000000..e2ae0cb
--- /dev/null
+++ b/deploy/roundcube/apache.conf.example
@@ -0,0 +1,23 @@
+
+ ServerName webmail.example.org
+ DocumentRoot /opt/roundcube/public_html
+
+ SSLEngine On
+ SSLCertificateFile /etc/ssl/coulobre-webmail/fullchain.pem
+ SSLCertificateKeyFile /etc/ssl/coulobre-webmail/privkey.pem
+
+
+ Options FollowSymLinks
+ AllowOverride None
+ DirectoryIndex index.php
+ Require all granted
+
+
+ SetHandler "proxy:unix:/run/php/coulobre-roundcube.sock|fcgi://localhost/"
+
+
+
+ Require all denied
+
+
+
diff --git a/deploy/roundcube/config.inc.php.example b/deploy/roundcube/config.inc.php.example
new file mode 100644
index 0000000..1f94133
--- /dev/null
+++ b/deploy/roundcube/config.inc.php.example
@@ -0,0 +1,12 @@
+ ['verify_peer' => true, 'verify_peer_name' => true],
+];
+$config['force_https'] = true;
+$config['session_samesite'] = 'Lax';
diff --git a/deploy/roundcube/coulobre_webmail.php b/deploy/roundcube/coulobre_webmail.php
new file mode 100644
index 0000000..669d630
--- /dev/null
+++ b/deploy/roundcube/coulobre_webmail.php
@@ -0,0 +1,151 @@
+add_hook('startup', [$this, 'startSignOn']);
+ $this->add_hook('authenticate', [$this, 'authenticateSignOn']);
+ }
+
+ public function startSignOn(array $args): array
+ {
+ if (!array_key_exists('_coulobre_ticket', $_POST)) {
+ return $args;
+ }
+
+ $roundcube = rcmail::get_instance();
+ $origin = $roundcube->config->get('coulobre_panel_origin', '');
+ if (
+ !is_string($origin)
+ || preg_match('~\Ahttps://(?:[a-z0-9.-]+|\[[a-f0-9:]+\])(?::[0-9]{1,5})?\z~iD', $origin) !== 1
+ ) {
+ $this->reject(503);
+ }
+
+ if (
+ ($_SERVER['REQUEST_METHOD'] ?? '') !== 'POST'
+ || !rcube_utils::https_check()
+ || ($_SERVER['HTTP_ORIGIN'] ?? '') !== $origin
+ ) {
+ $this->reject(403);
+ }
+
+ $ticket = $_POST['_coulobre_ticket'];
+ if (
+ count($_POST) !== 1
+ || !is_string($ticket)
+ || preg_match('/\A[A-Za-z0-9_-]{43}\z/D', $ticket) !== 1
+ ) {
+ $this->reject(400);
+ }
+
+ // Use the configured mail service for the selected address.
+ $host = $roundcube->config->get('imap_host');
+ if (
+ !is_string($host)
+ || preg_match('~\A(?:ssl|tls)://(?:[a-z0-9.-]+|\[[a-f0-9:]+\])(?::[0-9]{1,5})?\z~iD', $host) !== 1
+ ) {
+ $this->reject(503);
+ }
+ $keyPath = $roundcube->config->get('coulobre_bridge_key_file', '');
+ $key = is_string($keyPath) && is_readable($keyPath)
+ ? trim((string) @file_get_contents($keyPath, false, null, 0, 512))
+ : '';
+ if (
+ !function_exists('curl_init')
+ || preg_match('/\A[A-Za-z0-9_-]{32,128}\z/D', $key) !== 1
+ ) {
+ $this->reject(503);
+ }
+
+ $this->login = $this->exchangeTicket($origin, $key, $ticket);
+ $this->login['host'] = $host;
+
+ // Reset the previous mailbox session after the ticket is accepted.
+ $roundcube->kill_session();
+ return ['task' => 'login', 'action' => 'login'] + $args;
+ }
+
+ public function authenticateSignOn(array $args): array
+ {
+ if ($this->login === null) {
+ return $args;
+ }
+
+ $login = $this->login;
+ $this->login = null;
+ return [
+ 'host' => $login['host'],
+ 'user' => $login['user'],
+ 'pass' => $login['password'],
+ 'valid' => true,
+ // A first visit or a cross-site POST may have no Roundcube cookie.
+ 'cookiecheck' => false,
+ ] + $args;
+ }
+
+ private function exchangeTicket(string $origin, string $key, string $ticket): array
+ {
+ $connection = curl_init($origin . '/_bridge/roundcube/');
+ $body = '';
+ curl_setopt_array($connection, [
+ CURLOPT_POST => true,
+ CURLOPT_FOLLOWLOCATION => false,
+ CURLOPT_SSL_VERIFYPEER => true,
+ CURLOPT_SSL_VERIFYHOST => 2,
+ CURLOPT_CONNECTTIMEOUT => 4,
+ CURLOPT_TIMEOUT => 20,
+ CURLOPT_HTTPHEADER => [
+ 'Accept: application/json',
+ 'Content-Type: application/x-www-form-urlencoded',
+ 'X-Coulobre-Bridge-Key: ' . $key,
+ ],
+ CURLOPT_POSTFIELDS => http_build_query(['ticket' => $ticket]),
+ CURLOPT_WRITEFUNCTION => static function ($connection, string $chunk) use (&$body): int {
+ if (strlen($body) + strlen($chunk) > 4096) {
+ return 0;
+ }
+ $body .= $chunk;
+ return strlen($chunk);
+ },
+ ]);
+ $success = curl_exec($connection);
+ $status = curl_getinfo($connection, CURLINFO_RESPONSE_CODE);
+ if ($status === 404) {
+ $this->reject(403);
+ }
+ if (!$success || $status !== 200) {
+ $this->reject(503);
+ }
+
+ $login = json_decode($body, true);
+ if (
+ !is_array($login)
+ || !is_string($login['user'] ?? null)
+ || strlen($login['user']) > 254
+ || preg_match('/\A[a-z0-9][a-z0-9._-]*@[a-z0-9.-]+\z/D', $login['user']) !== 1
+ || !is_string($login['password'] ?? null)
+ || preg_match('/\A[A-Za-z0-9_-]{43}\z/D', $login['password']) !== 1
+ ) {
+ $this->reject(502);
+ }
+ return $login;
+ }
+
+ private function reject(int $status): never
+ {
+ http_response_code($status);
+ header('Cache-Control: private, no-store');
+ header('Content-Type: text/plain; charset=UTF-8');
+ header('Referrer-Policy: no-referrer');
+ exit('Webmail sign-in could not be completed. Open the mailbox from Coulobre Panel again.');
+ }
+}
diff --git a/deploy/roundcube/pool.conf.example b/deploy/roundcube/pool.conf.example
new file mode 100644
index 0000000..4207bb3
--- /dev/null
+++ b/deploy/roundcube/pool.conf.example
@@ -0,0 +1,15 @@
+[coulobre-roundcube]
+user = coulobre-roundcube
+group = coulobre-roundcube
+listen = /run/php/coulobre-roundcube.sock
+listen.owner = www-data
+listen.group = www-data
+listen.mode = 0660
+pm = ondemand
+pm.max_children = 4
+clear_env = yes
+security.limit_extensions = .php
+php_admin_flag[display_errors] = off
+php_admin_flag[session.use_strict_mode] = on
+php_admin_flag[session.cookie_secure] = on
+php_admin_flag[session.cookie_httponly] = on
diff --git a/docs/deployment.md b/docs/deployment.md
index 155e10e..033ed42 100644
--- a/docs/deployment.md
+++ b/docs/deployment.md
@@ -840,6 +840,76 @@ managed login. Existing database grants scope the session to the selected
database. Sign out of phpMyAdmin to end its session.
[phpMyAdmin signon mode](https://docs.phpmyadmin.net/en/latest/config.html#example-for-signon-authentication)
+### Open a mailbox in Roundcube
+
+On Ubuntu 26.04 with PHP 8.5, use the current Roundcube 1.7 Complete
+release from [Roundcube Downloads](https://roundcube.net/download/). Verify
+the archive and install Roundcube in `/opt/roundcube` following the
+[upstream manual setup](https://github.com/roundcube/roundcubemail/wiki/Installation).
+The Ubuntu 26.04 package at version 1.6.11 cannot start with PHP 8.5.
+Install the required PHP extensions for Roundcube and its database, as
+well as `php8.5-curl` for the bridge.
+
+Use the mail server already configured for Coulobre. Confirm that a
+mailbox can sign in over TLS using its full email address. Configure a
+single IMAP host with a trusted certificate and configure Roundcube's SMTP
+submission settings for sending mail. The same setup works with the panel's
+local or remote [mailbox credential service](#enable-connection-details-for-remote-mailboxes).
+
+Use a dedicated PHP-FPM account. Grant that account read access to the
+Roundcube configuration and bridge key, access to the database, and write
+access to the Roundcube temporary files and logs. Use the same account for
+Roundcube maintenance jobs. Keep the application code and configuration
+owned by root.
+
+```sh
+sudo useradd --system --user-group --no-create-home --shell /usr/sbin/nologin coulobre-roundcube
+sudo install -d -o root -g coulobre-roundcube -m 0750 /etc/coulobre-roundcube
+sudo install -o root -g coulobre-roundcube -m 0640 /dev/null /etc/coulobre-roundcube/bridge.key
+sudo sh -c 'openssl rand -hex 32 > /etc/coulobre-roundcube/bridge.key'
+sudo install -D -m 0644 deploy/roundcube/coulobre_webmail.php \
+ /opt/roundcube/plugins/coulobre_webmail/coulobre_webmail.php
+sudo install -m 0644 deploy/roundcube/pool.conf.example \
+ /etc/php/8.5/fpm/pool.d/coulobre-roundcube.conf
+sudo install -o root -g coulobre-roundcube -m 0640 deploy/roundcube/config.inc.php.example \
+ /etc/coulobre-roundcube/webmail.inc.php
+sudoedit /etc/coulobre-roundcube/webmail.inc.php
+```
+
+Set the panel origin to the exact HTTPS origin users visit, including a
+non-default port if one is used. Set `imap_host` to the mail server's TLS
+endpoint. Include the example from the end of Roundcube's
+`/opt/roundcube/config/config.inc.php`.
+
+```php
+require '/etc/coulobre-roundcube/webmail.inc.php';
+```
+
+Configure the webmail site with `deploy/roundcube/apache.conf.example`.
+Substitute the hostname and certificate paths, enable Apache's `ssl` and
+`proxy_fcgi` modules, and enable the site. The example serves
+`/opt/roundcube/public_html` through the dedicated FPM socket and blocks
+the web installer. Run the Apache configuration test and reload Apache
+and PHP-FPM. Keep certificate verification enabled between Roundcube and
+both the panel and the IMAP server.
+
+On the panel, set the following values in `/etc/coulobre/panel.env`. Use the
+same random key from `bridge.key` for Roundcube only. Set the webmail URL to
+the canonical HTTPS base URL so a form POST can arrive without a redirect.
+
+```ini
+COULOBRE_ROUNDCUBE_URL=https://webmail.example.org
+COULOBRE_ROUNDCUBE_BRIDGE_KEY=
+```
+
+Run `panel_manage migrate --noinput`, collect static files, and restart
+`coulobre-panel`. Use **Open webmail** beside a mailbox in the account
+view. The browser carries a single-use ticket valid for 45 seconds.
+Roundcube exchanges the ticket with Coulobre over HTTPS and uses its
+ordinary IMAP login. The exchange appears in **Service credential
+accesses**. Opening another mailbox in the same browser switches the
+current Roundcube session.
+
## Publish local DNS zones from the panel
To publish to BIND9 on another host, use the
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 %}
+
+ {% endif %}
{% if show_mailbox_credentials %}
{% 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"
|