From 43d03d207ebcbdf6ce52f6e6754c711dea4b9d97 Mon Sep 17 00:00:00 2001 From: Peter van Arkel Date: Sat, 21 Nov 2026 10:30:36 +0100 Subject: [PATCH 1/2] Provision website HTTPS through a restricted Unix socket --- deploy/systemd/coulobre-https-apply.socket | 14 +++ deploy/systemd/coulobre-https-apply@.service | 20 +++++ .../hosting/test_web_node_manifest.py | 25 +++++- src/coulobre/hosting/test_web_node_tls.py | 68 ++++++++++++++- src/coulobre/web_node.py | 11 +++ src/coulobre/web_node_tls.py | 85 +++++++++++++++++-- 6 files changed, 214 insertions(+), 9 deletions(-) create mode 100644 deploy/systemd/coulobre-https-apply.socket create mode 100644 deploy/systemd/coulobre-https-apply@.service diff --git a/deploy/systemd/coulobre-https-apply.socket b/deploy/systemd/coulobre-https-apply.socket new file mode 100644 index 0000000..841960c --- /dev/null +++ b/deploy/systemd/coulobre-https-apply.socket @@ -0,0 +1,14 @@ +[Unit] +Description=Coulobre local website HTTPS socket + +[Socket] +ListenStream=/run/coulobre-https-apply.sock +SocketUser=root +SocketGroup=coulobre-https-provisioning +SocketMode=0660 +Accept=yes +MaxConnections=1 +RemoveOnStop=true + +[Install] +WantedBy=sockets.target diff --git a/deploy/systemd/coulobre-https-apply@.service b/deploy/systemd/coulobre-https-apply@.service new file mode 100644 index 0000000..542b3eb --- /dev/null +++ b/deploy/systemd/coulobre-https-apply@.service @@ -0,0 +1,20 @@ +[Unit] +Description=Coulobre local website HTTPS request +After=apache2.service php8.5-fpm.service +CollectMode=inactive-or-failed + +[Service] +Type=exec +User=root +WorkingDirectory=/opt/coulobre +UMask=0022 +ExecStart=/opt/coulobre/bin/coulobre-web-node https-request +StandardInput=socket +StandardOutput=socket +StandardError=journal +RuntimeMaxSec=3min +KillSignal=SIGINT +KillMode=mixed +NoNewPrivileges=true +PrivateTmp=true +ProtectHome=true diff --git a/src/coulobre/hosting/test_web_node_manifest.py b/src/coulobre/hosting/test_web_node_manifest.py index 2c08ac7..bc7bf44 100644 --- a/src/coulobre/hosting/test_web_node_manifest.py +++ b/src/coulobre/hosting/test_web_node_manifest.py @@ -50,13 +50,13 @@ class WebActivationRequestTests(SimpleTestCase): patch("coulobre.web_node_apply.apply_site") ) - def request(self, data): + def request(self, data, *, command="apply-request"): output = StringIO() with ( patch("sys.stdin", SimpleNamespace(buffer=BytesIO(data))), redirect_stdout(output), ): - code = main(["apply-request"]) + code = main([command]) return code, json.loads(output.getvalue()) def test_replies_with_the_identity_of_the_applied_manifest(self): @@ -99,3 +99,24 @@ class WebActivationRequestTests(SimpleTestCase): "problem": "The primary domain is already reserved.", }, ) + + def test_https_request_uses_only_the_site_manifest(self): + manifest = self.site.manifest() + with patch("coulobre.web_node_tls.provision_https") as provision: + code, reply = self.request( + json.dumps(manifest | {"webroot": "/tmp"}).encode(), + command="https-request", + ) + self.assertEqual(code, 1) + self.assertEqual(reply["state"], "failed") + provision.assert_not_called() + + code, reply = self.request( + json.dumps(manifest).encode(), command="https-request" + ) + self.assertEqual(code, 0) + self.assertEqual( + reply, manifest | {"state": "configured", "problem": None} + ) + provision.assert_called_once_with(self.site) + self.apply.assert_not_called() diff --git a/src/coulobre/hosting/test_web_node_tls.py b/src/coulobre/hosting/test_web_node_tls.py index cd8ad73..1bc549f 100644 --- a/src/coulobre/hosting/test_web_node_tls.py +++ b/src/coulobre/hosting/test_web_node_tls.py @@ -1,4 +1,5 @@ from pathlib import Path +from subprocess import DEVNULL, CalledProcessError from tempfile import TemporaryDirectory from unittest.mock import call, patch @@ -6,7 +7,12 @@ from django.test import SimpleTestCase from coulobre.web_node import WebSite from coulobre.web_node_apply import SitePaths -from coulobre.web_node_tls import enable_https, https_status +from coulobre.web_node_tls import ( + enable_https, + https_status, + provision_https, + request_certificate, +) class WebNodeTLSTests(SimpleTestCase): @@ -47,6 +53,12 @@ class WebNodeTLSTests(SimpleTestCase): patch("coulobre.web_node_tls.STATE_DIRECTORY", self.state) ) self.enterContext(patch("coulobre.web_node_tls.CERTBOT_ROOT", certbot)) + self.webroot = directory / "coulobre-acme" + challenge = self.webroot / ".well-known" / "acme-challenge" + challenge.mkdir(parents=True) + self.enterContext( + patch("coulobre.web_node_tls.ACME_WEBROOT", self.webroot) + ) self.enterContext( patch( "coulobre.web_node_tls.SitePaths.for_site", return_value=paths @@ -169,3 +181,57 @@ class WebNodeTLSTests(SimpleTestCase): self.assertEqual(report["state"], "needs_attention") self.assertIn("Existing configuration differs", report["problem"]) self.assertEqual(self.tls.read_text(), "changed") + + def test_panel_retry_reuses_an_existing_lineage(self): + with patch("coulobre.web_node_tls.request_certificate") as certbot: + provision_https(self.site) + + certbot.assert_not_called() + self.assertTrue(self.enabled.is_symlink()) + + def test_unreserved_site_cannot_issue_a_certificate(self): + self.reservation.side_effect = ValueError("Apply the site first.") + with ( + patch("coulobre.web_node_tls.request_certificate") as certbot, + self.assertRaisesMessage(ValueError, "Apply the site first."), + ): + provision_https(self.site) + + certbot.assert_not_called() + self.assertFalse(self.enabled.is_symlink()) + + def test_certbot_uses_the_fixed_webroot_and_site_identity(self): + with patch("coulobre.web_node_tls.subprocess.run") as certbot: + request_certificate(self.site) + + (command,) = certbot.call_args.args + self.assertEqual( + command, + ( + "/usr/bin/certbot", + "certonly", + "--non-interactive", + "--keep-until-expiring", + "--webroot", + "--webroot-path", + str(self.webroot), + "--cert-name", + "coulobre-42", + "--domains", + "example.org", + ), + ) + self.assertEqual(certbot.call_args.kwargs["stderr"], DEVNULL) + self.assertEqual(certbot.call_args.kwargs["timeout"], 120) + + def test_certbot_diagnostics_stay_on_the_web_node(self): + error = CalledProcessError(1, "certbot", stderr="private account info") + with ( + patch("coulobre.web_node_tls.subprocess.run", side_effect=error), + self.assertRaisesMessage( + ValueError, "Check its account" + ) as failure, + ): + request_certificate(self.site) + + self.assertNotIn("private account info", str(failure.exception)) diff --git a/src/coulobre/web_node.py b/src/coulobre/web_node.py index 4b42ecd..f2d4200 100644 --- a/src/coulobre/web_node.py +++ b/src/coulobre/web_node.py @@ -100,6 +100,10 @@ def main(argv=None): help="Enable HTTPS with an existing Certbot certificate.", ) https.add_argument("manifest", type=Path) + commands.add_parser( + "https-request", + help="Obtain and enable HTTPS from a site manifest on standard input.", + ) https_status = commands.add_parser( "https-status", help="Check a site's local HTTPS configuration." ) @@ -122,6 +126,13 @@ def main(argv=None): MANIFEST_VERSION, WebSite.from_manifest, apply_site ) + if args.command == "https-request": + from .web_node_tls import provision_https + + return serve_apply_request( + MANIFEST_VERSION, WebSite.from_manifest, provision_https + ) + try: payload = json.loads(args.manifest.read_text(encoding="utf-8")) site = WebSite.from_manifest(payload) diff --git a/src/coulobre/web_node_tls.py b/src/coulobre/web_node_tls.py index 3ec8204..bfd679d 100644 --- a/src/coulobre/web_node_tls.py +++ b/src/coulobre/web_node_tls.py @@ -1,6 +1,7 @@ import fcntl import os import ssl +import subprocess from contextlib import contextmanager from pathlib import Path @@ -19,6 +20,70 @@ from .web_node_apply import ( ) CERTBOT_ROOT = Path("/etc/letsencrypt") +ACME_WEBROOT = Path("/var/www/coulobre-acme") + + +def provision_https(site): + if os.geteuid() != 0: + raise ValueError("Run https-request as root on the web node.") + + with locked_web_node(fcntl.LOCK_SH): + check_https_prerequisites(site, SitePaths.for_site(site)) + + if not os.path.lexists(certbot_lineage(site)): + try: + require_root_directory(CERTBOT_ROOT) + except FileNotFoundError: + raise ValueError( + "Register a Certbot account on the web node." + ) from None + challenge = ACME_WEBROOT / ".well-known" / "acme-challenge" + try: + require_root_directory(challenge) + except FileNotFoundError: + raise ValueError( + "Configure the Certbot HTTP-01 webroot on the web node." + ) from None + request_certificate(site) + + enable_https(site) + + +def request_certificate(site): + command = ( + "/usr/bin/certbot", + "certonly", + "--non-interactive", + "--keep-until-expiring", + "--webroot", + "--webroot-path", + str(ACME_WEBROOT), + "--cert-name", + certbot_lineage(site).name, + "--domains", + site.domain, + ) + try: + subprocess.run( + command, + check=True, + stdin=subprocess.DEVNULL, + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + timeout=120, + env={"PATH": "/usr/sbin:/usr/bin:/sbin:/bin", "LANG": "C"}, + ) + except FileNotFoundError: + raise ValueError("Install Certbot on the web node.") from None + except subprocess.TimeoutExpired: + raise ValueError( + "Certbot timed out. Check the HTTP-01 route and the Certbot log." + ) from None + except subprocess.CalledProcessError: + raise ValueError( + "Certbot could not obtain the certificate. Check its account, " + "the HTTP-01 route, and the Certbot log on the web node." + ) from None def enable_https(site): @@ -28,10 +93,7 @@ def enable_https(site): paths = SitePaths.for_site(site) apache, enabled = https_paths(paths) with locked_web_node(fcntl.LOCK_EX): - check_reservation(site) - check_installation(site, paths) - if "ssl_module" not in run("/usr/sbin/apache2ctl", "-M"): - raise ValueError("Enable Apache's ssl module on the web node.") + check_https_prerequisites(site, paths) config = https_configuration(site) with configuration_installation() as (created, reload_attempts): install_configuration(apache, config, created) @@ -41,6 +103,13 @@ def enable_https(site): run("/usr/sbin/service", "apache2", "reload") +def check_https_prerequisites(site, paths): + check_reservation(site) + check_installation(site, paths) + if "ssl_module" not in run("/usr/sbin/apache2ctl", "-M"): + raise ValueError("Enable Apache's ssl module on the web node.") + + def https_status(site): if os.geteuid() != 0: raise ValueError("Run https-status as root on the web node.") @@ -84,9 +153,13 @@ def https_paths(paths): return paths.apache.with_name(name), paths.enabled.with_name(name) +def certbot_lineage(site): + return CERTBOT_ROOT / "live" / f"coulobre-{site.account_id}" + + def https_configuration(site): - name = f"coulobre-{site.account_id}" - lineage = CERTBOT_ROOT / "live" / name + lineage = certbot_lineage(site) + name = lineage.name archive = CERTBOT_ROOT / "archive" / name for directory in (lineage, archive): try: -- 2.43.0 From 4d6aa0c281369c23ecf6c4cf13a79a23e0cf2af8 Mon Sep 17 00:00:00 2001 From: Peter van Arkel Date: Sat, 21 Nov 2026 10:31:32 +0100 Subject: [PATCH 2/2] Add website HTTPS requests to Coulobre Panel --- deploy/panel.env.example | 1 + .../coulobre-https-provisioner.service | 26 ++++ docs/deployment.md | 42 ++++++ docs/development.md | 5 + .../hosting/migrations/0018_web_https.py | 50 +++++++ src/coulobre/hosting/models.py | 18 +++ src/coulobre/hosting/node_client.py | 6 + src/coulobre/hosting/tasks.py | 30 ++++ .../templates/hosting/plan_detail.html | 18 ++- .../hosting/resource_provisioning.html | 2 +- src/coulobre/hosting/test_web_https.py | 132 ++++++++++++++++++ src/coulobre/hosting/urls.py | 5 + src/coulobre/hosting/views.py | 29 +++- src/coulobre/settings.py | 7 + 14 files changed, 368 insertions(+), 3 deletions(-) create mode 100644 deploy/systemd/coulobre-https-provisioner.service create mode 100644 src/coulobre/hosting/migrations/0018_web_https.py create mode 100644 src/coulobre/hosting/test_web_https.py diff --git a/deploy/panel.env.example b/deploy/panel.env.example index 25f85f6..90ed0f3 100644 --- a/deploy/panel.env.example +++ b/deploy/panel.env.example @@ -9,6 +9,7 @@ COULOBRE_DB_PASSWORD= COULOBRE_DB_HOST=/run/mysqld/mysqld.sock COULOBRE_BROKER_URL=amqp://coulobre:@127.0.0.1:5672/coulobre # COULOBRE_LOCAL_WEB_ACTIVATION=1 +# COULOBRE_LOCAL_WEB_HTTPS=1 # COULOBRE_LOCAL_DATABASE_PROVISIONING=1 # COULOBRE_LOCAL_DNS_PUBLISHING=1 # COULOBRE_LOCAL_MAILBOX_PROVISIONING=1 diff --git a/deploy/systemd/coulobre-https-provisioner.service b/deploy/systemd/coulobre-https-provisioner.service new file mode 100644 index 0000000..7d253c3 --- /dev/null +++ b/deploy/systemd/coulobre-https-provisioner.service @@ -0,0 +1,26 @@ +[Unit] +Description=Coulobre Panel website HTTPS worker +Requires=coulobre-https-apply.socket +Wants=network-online.target +After=network-online.target coulobre-https-apply.socket mariadb.service rabbitmq-server.service + +[Service] +Type=exec +User=coulobre-https-provisioner +Group=coulobre-https-provisioner +SupplementaryGroups=coulobre-https-provisioning +EnvironmentFile=/etc/coulobre/panel.env +WorkingDirectory=/opt/coulobre +UMask=0077 +ExecStart=/opt/coulobre/bin/celery -A coulobre worker --loglevel=INFO --queues=coulobre-web-https --hostname=https-provisioner@%H --concurrency=1 +KillMode=mixed +TimeoutStopSec=4min +Restart=on-failure +RestartSec=5s +NoNewPrivileges=true +PrivateTmp=true +ProtectHome=true +ProtectSystem=strict + +[Install] +WantedBy=multi-user.target diff --git a/docs/deployment.md b/docs/deployment.md index a5a2930..dab51f2 100644 --- a/docs/deployment.md +++ b/docs/deployment.md @@ -219,6 +219,48 @@ web node and enable its HTTPS virtual host. Each site uses its own certificate. The renewal hook reloads Apache after Certbot renews it. [Hosted website HTTPS setup](development.md#enable-https-for-a-hosted-website) +### Request HTTPS from the panel + +Set up Apache's HTTP-01 webroot and the Certbot renewal hook on the local +web node. Register a Certbot account if this node does not already have one, +using an email address monitored by the operator. +[Hosted website HTTPS setup](development.md#enable-https-for-a-hosted-website) + +```sh +sudo certbot register --email hostmaster@example.org --agree-tos +sudo groupadd --system coulobre-https-provisioning +sudo useradd --system --user-group --no-create-home --home-dir /nonexistent \ + --shell /usr/sbin/nologin coulobre-https-provisioner +sudo install -m 0644 deploy/systemd/coulobre-https-apply.socket \ + deploy/systemd/coulobre-https-apply@.service \ + deploy/systemd/coulobre-https-provisioner.service /etc/systemd/system/ +sudo systemctl daemon-reload +``` + +Set `COULOBRE_LOCAL_WEB_HTTPS=1` in `/etc/coulobre/panel.env`, then apply +pending migrations and restart the panel services. + +```sh +panel_manage migrate --noinput +sudo systemctl restart coulobre-panel coulobre-worker coulobre-beat +sudo systemctl enable --now coulobre-https-apply.socket \ + coulobre-https-provisioner.service +``` + +On an active site's Apache preview, select **Enable HTTPS** and use +**Refresh status** to follow the request. This requires the **Can add +website HTTPS request** permission and access to view hosting accounts +and web provisioning plans. The worker uses the manifest's primary +domain and keeps Certbot logs and credentials on the web node. If the +request fails, check the diagnostic and use **Retry HTTPS** after +resolving the problem. Certbot handles later renewals. + +The panel uses HTTP-01 for initial issuance. For DNS validation, obtain +the certificate on the web node with its configured Certbot DNS plugin +and the expected lineage name. The panel can then enable HTTPS using +that certificate. Certbot renews it with its saved authenticator. +[Certbot DNS plugins](https://eff-certbot.readthedocs.io/en/stable/using.html#dns-plugins) + ## Provision local databases from the panel Enable the [database provisioning socket](development.md#enable-local-database-provisioning) diff --git a/docs/development.md b/docs/development.md index 3299dde..fe65d94 100644 --- a/docs/development.md +++ b/docs/development.md @@ -727,6 +727,11 @@ can use a DNS plugin for validation. Request the certificate under the same lineage name before running `enable-https`. [Certbot certificate guide](https://eff-certbot.readthedocs.io/en/stable/using.html) +To request and enable HTTPS from the panel, set up the dedicated socket +and worker on the local web node. They use the same Certbot webroot, +lineage name, and renewal hook. +[Panel HTTPS setup](deployment.md#request-https-from-the-panel) + ### Enable local web activation On a web node with the same Apache and PHP-FPM setup, systemd can accept local diff --git a/src/coulobre/hosting/migrations/0018_web_https.py b/src/coulobre/hosting/migrations/0018_web_https.py new file mode 100644 index 0000000..e2a36bf --- /dev/null +++ b/src/coulobre/hosting/migrations/0018_web_https.py @@ -0,0 +1,50 @@ +# Generated by Django 5.2.19 on 2026-11-21 01:46 + +import django.db.models.deletion +import django.utils.timezone +from django.db import migrations, models + + +class Migration(migrations.Migration): + dependencies = [ + ("hosting", "0017_customer_impersonation"), + ] + + operations = [ + migrations.CreateModel( + name="WebHTTPS", + fields=[ + ( + "id", + models.BigAutoField( + auto_created=True, + primary_key=True, + serialize=False, + verbose_name="ID", + ), + ), + ( + "requested_at", + models.DateTimeField(default=django.utils.timezone.now), + ), + ( + "last_dispatched_at", + models.DateTimeField(blank=True, null=True), + ), + ("started_at", models.DateTimeField(blank=True, null=True)), + ("finished_at", models.DateTimeField(blank=True, null=True)), + ("problem", models.TextField(blank=True)), + ( + "plan", + models.OneToOneField( + on_delete=django.db.models.deletion.CASCADE, + related_name="https", + to="hosting.webprovisioningplan", + ), + ), + ], + options={ + "verbose_name": "website HTTPS request", + }, + ), + ] diff --git a/src/coulobre/hosting/models.py b/src/coulobre/hosting/models.py index 2bd3e9c..0ebbbde 100644 --- a/src/coulobre/hosting/models.py +++ b/src/coulobre/hosting/models.py @@ -290,6 +290,15 @@ class WebProvisioningPlan(models.Model): and self.primary_domain == self.account.primary_domain ) + @property + def can_enable_https(self): + activation = getattr(self, "activation", None) + return ( + self.can_export + and activation is not None + and activation.state == "configured" + ) + class ProvisioningJobManager(models.Manager): def queue(self, **target): @@ -334,6 +343,15 @@ class WebActivation(ProvisioningJob): ) +class WebHTTPS(ProvisioningJob): + plan = models.OneToOneField( + WebProvisioningPlan, on_delete=models.CASCADE, related_name="https" + ) + + class Meta: + verbose_name = "website HTTPS request" + + class DatabaseProvisioning(ProvisioningJob): database = models.OneToOneField( HostingDatabase, on_delete=models.CASCADE, related_name="provisioning" diff --git a/src/coulobre/hosting/node_client.py b/src/coulobre/hosting/node_client.py index b4a2e4e..b246da1 100644 --- a/src/coulobre/hosting/node_client.py +++ b/src/coulobre/hosting/node_client.py @@ -10,6 +10,12 @@ def activate_local_site(site): ) +def enable_local_https(site): + apply_on_local_node( + site, "/run/coulobre-https-apply.sock", "web node", "HTTPS request" + ) + + def provision_local_database(database): apply_on_local_node( database, diff --git a/src/coulobre/hosting/tasks.py b/src/coulobre/hosting/tasks.py index d61d12b..72586af 100644 --- a/src/coulobre/hosting/tasks.py +++ b/src/coulobre/hosting/tasks.py @@ -13,10 +13,12 @@ from .models import ( DnsPublication, MailboxProvisioning, WebActivation, + WebHTTPS, WebProvisioningPlan, ) from .node_client import ( activate_local_site, + enable_local_https, provision_local_database, provision_local_mailbox, publish_local_zone, @@ -24,6 +26,7 @@ from .node_client import ( REDISPATCH_AFTER = timedelta(minutes=5) WEB_ACTIVATION_QUEUE = "coulobre-web-activation" +WEB_HTTPS_QUEUE = "coulobre-web-https" DATABASE_PROVISIONING_QUEUE = "coulobre-database-provisioning" DNS_PUBLISHING_QUEUE = "coulobre-dns-publishing" MAILBOX_PROVISIONING_QUEUE = "coulobre-mailbox-provisioning" @@ -72,6 +75,12 @@ def dispatch_web_activations(): ) +@shared_task +def dispatch_web_https(): + if settings.LOCAL_WEB_HTTPS: + dispatch_provisioning_jobs(WebHTTPS, enable_web_https, WEB_HTTPS_QUEUE) + + @shared_task def dispatch_database_provisioning(): if settings.LOCAL_DATABASE_PROVISIONING: @@ -139,6 +148,27 @@ def apply_web_activation(activation): activate_local_site(WebSite(plan.account_id, plan.primary_domain)) +@shared_task(acks_late=True, reject_on_worker_lost=True) +def enable_web_https(request_id): + if settings.LOCAL_WEB_HTTPS: + run_provisioning_job( + WebHTTPS.objects.select_related( + "plan__account", "plan__activation" + ), + request_id, + apply_web_https, + "Could not contact the local HTTPS service. " + "Check its socket and try again.", + ) + + +def apply_web_https(provisioning): + plan = provisioning.plan + if not plan.can_enable_https: + raise ValueError("Activate the site for the current domain first.") + enable_local_https(WebSite(plan.account_id, plan.primary_domain)) + + @shared_task(acks_late=True, reject_on_worker_lost=True) def provision_database(provisioning_id): if settings.LOCAL_DATABASE_PROVISIONING: diff --git a/src/coulobre/hosting/templates/hosting/plan_detail.html b/src/coulobre/hosting/templates/hosting/plan_detail.html index eb5dc4c..7de41d2 100644 --- a/src/coulobre/hosting/templates/hosting/plan_detail.html +++ b/src/coulobre/hosting/templates/hosting/plan_detail.html @@ -7,7 +7,7 @@

Apache preview

{{ plan.primary_domain }}

- {% if not plan.completed_at or manage_activation and plan.activation and not plan.activation.finished_at %} + {% if not plan.completed_at or manage_activation and plan.activation and not plan.activation.finished_at or manage_https and plan.https and not plan.https.finished_at %} Refresh status {% endif %} @@ -66,4 +66,20 @@ {% endif %} {% endwith %} {% endif %} + {% if manage_https %} + {% with provisioning=plan.https %} + {% if provisioning or local_https_enabled and plan.can_enable_https %} +
+
+

Website HTTPS

+ {% if local_https_enabled and plan.can_enable_https %} + {% url 'panel:plan_https' plan.pk as https_action %} + {% endif %} + {% include "hosting/resource_provisioning.html" with enabled=https_action action=https_action resource=plan.primary_domain provision_label="Enable HTTPS" retry_label="Retry HTTPS" %} +
+ {% if provisioning.problem %}

{{ provisioning.problem }}

{% endif %} +
+ {% endif %} + {% endwith %} + {% endif %} {% endblock %} diff --git a/src/coulobre/hosting/templates/hosting/resource_provisioning.html b/src/coulobre/hosting/templates/hosting/resource_provisioning.html index bec634d..0f286e5 100644 --- a/src/coulobre/hosting/templates/hosting/resource_provisioning.html +++ b/src/coulobre/hosting/templates/hosting/resource_provisioning.html @@ -12,7 +12,7 @@
{% csrf_token %} {% if provisioning %} - + {% else %} {% endif %} diff --git a/src/coulobre/hosting/test_web_https.py b/src/coulobre/hosting/test_web_https.py new file mode 100644 index 0000000..d5cfd17 --- /dev/null +++ b/src/coulobre/hosting/test_web_https.py @@ -0,0 +1,132 @@ +from unittest.mock import patch + +from django.contrib.auth import get_user_model +from django.contrib.auth.models import Permission +from django.test import TestCase, override_settings +from django.urls import reverse +from django.utils import timezone + +from coulobre.web_node import WebSite + +from .models import ( + HostingAccount, + WebActivation, + WebHTTPS, + WebProvisioningPlan, +) +from .tasks import WEB_HTTPS_QUEUE, dispatch_web_https, enable_web_https + + +@override_settings(LOCAL_WEB_HTTPS=True) +class WebHTTPSTests(TestCase): + @classmethod + def setUpTestData(cls): + cls.operator = get_user_model().objects.create_superuser("operator") + cls.account = HostingAccount.objects.create( + name="Example site", primary_domain="site.example" + ) + cls.plan = WebProvisioningPlan.objects.create( + account=cls.account, + primary_domain=cls.account.primary_domain, + apache_config="Rendered Apache configuration", + completed_at=timezone.now(), + ) + + def setUp(self): + self.client.force_login(self.operator) + self.url = reverse("panel:plan_https", args=[self.plan.pk]) + self.detail = reverse("panel:plan", args=[self.plan.pk]) + + def activate_site(self): + WebActivation.objects.create( + plan=self.plan, finished_at=timezone.now() + ) + + def test_requires_an_active_site_for_the_current_domain(self): + self.assertEqual(self.client.post(self.url).status_code, 409) + self.assertNotContains(self.client.get(self.detail), "Enable HTTPS") + self.activate_site() + self.account.primary_domain = "new.example" + self.account.save(update_fields=["primary_domain"]) + self.assertEqual(self.client.post(self.url).status_code, 409) + self.assertFalse(WebHTTPS.objects.exists()) + + def test_operator_can_queue_once_and_track_https(self): + self.activate_site() + self.assertContains(self.client.get(self.detail), "Enable HTTPS") + self.assertEqual(self.client.get(self.url).status_code, 405) + self.assertRedirects(self.client.post(self.url), self.detail) + self.client.post(self.url) + request = WebHTTPS.objects.get(plan=self.plan) + self.assertContains(self.client.get(self.detail), "Refresh status") + + with patch( + "coulobre.hosting.tasks.enable_web_https.apply_async" + ) as send: + dispatch_web_https() + send.assert_called_once_with( + args=[request.pk], queue=WEB_HTTPS_QUEUE, retry=False + ) + + with patch("coulobre.hosting.tasks.enable_local_https") as enable: + enable_web_https(request.pk) + enable_web_https(request.pk) + enable.assert_called_once_with( + WebSite(self.account.pk, self.account.primary_domain) + ) + request.refresh_from_db() + self.assertEqual(request.state, "configured") + self.assertNotContains(self.client.get(self.detail), "Enable HTTPS") + + def test_failed_attempt_can_be_retried(self): + self.activate_site() + request = WebHTTPS.objects.create(plan=self.plan) + with patch( + "coulobre.hosting.tasks.enable_local_https", + side_effect=ValueError("Check the HTTP-01 route."), + ): + enable_web_https(request.pk) + response = self.client.get(self.detail) + self.assertContains(response, "Check the HTTP-01 route.") + self.assertContains(response, "Retry HTTPS") + + self.assertRedirects(self.client.post(self.url), self.detail) + request.refresh_from_db() + self.assertEqual(request.state, "queued") + self.assertIsNone(request.started_at) + self.assertEqual(request.problem, "") + + def test_worker_rechecks_the_domain_before_requesting_a_certificate(self): + self.activate_site() + request = WebHTTPS.objects.create(plan=self.plan) + self.account.primary_domain = "new.example" + self.account.save(update_fields=["primary_domain"]) + + with patch("coulobre.hosting.tasks.enable_local_https") as enable: + enable_web_https(request.pk) + enable.assert_not_called() + request.refresh_from_db() + self.assertEqual(request.state, "failed") + + def test_activation_permission_does_not_grant_https_access(self): + self.activate_site() + reader = get_user_model().objects.create_user("reader", is_staff=True) + reader.user_permissions.add( + *Permission.objects.filter( + content_type__app_label="hosting", + codename__in=( + "view_hostingaccount", + "view_webprovisioningplan", + "add_webactivation", + ), + ) + ) + self.client.force_login(reader) + self.assertNotContains(self.client.get(self.detail), "Enable HTTPS") + self.assertEqual(self.client.post(self.url).status_code, 403) + + @override_settings(LOCAL_WEB_HTTPS=False) + def test_feature_flag_disables_requests(self): + self.activate_site() + self.assertNotContains(self.client.get(self.detail), "Enable HTTPS") + self.assertEqual(self.client.post(self.url).status_code, 404) diff --git a/src/coulobre/hosting/urls.py b/src/coulobre/hosting/urls.py index f5664e0..ff9948c 100644 --- a/src/coulobre/hosting/urls.py +++ b/src/coulobre/hosting/urls.py @@ -121,6 +121,11 @@ urlpatterns = [ views.RequestWebActivation.as_view(), name="plan_activate", ), + path( + "plans//https/", + views.RequestWebHTTPS.as_view(), + name="plan_https", + ), path( "plans//smoke-bundle/", views.DownloadWebPlan.as_view(), diff --git a/src/coulobre/hosting/views.py b/src/coulobre/hosting/views.py index 4bd0b58..54c7bbf 100644 --- a/src/coulobre/hosting/views.py +++ b/src/coulobre/hosting/views.py @@ -55,6 +55,7 @@ from .models import ( MailboxProvisioning, Reseller, WebActivation, + WebHTTPS, WebProvisioningPlan, ) from .reseller_accounts import create_reseller_account @@ -71,6 +72,7 @@ VIEW_DATABASES = "hosting.view_hostingdatabase" VIEW_DNS_ZONES = "hosting.view_hostingdnszone" VIEW_MAILBOXES = "hosting.view_hostingmailbox" ACTIVATE_WEB = (VIEW_ACCOUNTS, VIEW_PLANS, "hosting.add_webactivation") +ENABLE_WEB_HTTPS = (VIEW_ACCOUNTS, VIEW_PLANS, "hosting.add_webhttps") PROVISION_DATABASE = ( VIEW_ACCOUNTS, VIEW_DATABASES, @@ -717,7 +719,7 @@ class PlanList(TenantScopeMixin, PermissionRequiredMixin, ListView): class PlanDetail(TenantScopeMixin, PermissionRequiredMixin, DetailView): queryset = WebProvisioningPlan.objects.select_related( - "account", "activation" + "account", "activation", "https" ) permission_required = VIEW_PLANS reseller_relation = "account__reseller" @@ -730,6 +732,9 @@ class PlanDetail(TenantScopeMixin, PermissionRequiredMixin, DetailView): manage_activation=not is_tenant(user) and user.has_perms(ACTIVATE_WEB), local_activation_enabled=settings.LOCAL_WEB_ACTIVATION, + manage_https=not is_tenant(user) + and user.has_perms(ENABLE_WEB_HTTPS), + local_https_enabled=settings.LOCAL_WEB_HTTPS, **kwargs, ) @@ -755,6 +760,28 @@ class RequestWebActivation( return redirect("panel:plan", pk=plan.pk) +class RequestWebHTTPS( + OperatorOnlyMixin, PermissionRequiredMixin, SingleObjectMixin, View +): + queryset = WebProvisioningPlan.objects.select_related( + "account", "activation" + ) + permission_required = ENABLE_WEB_HTTPS + + def post(self, request, *args, **kwargs): + if not settings.LOCAL_WEB_HTTPS: + raise Http404 + plan = self.get_object() + if not plan.can_enable_https: + return HttpResponse( + "Activate the site for the current domain first.", + status=409, + content_type="text/plain", + ) + WebHTTPS.objects.queue(plan=plan) + return redirect("panel:plan", pk=plan.pk) + + class DownloadWebPlan(OperatorOnlyMixin, PlanDetail): manifest = False diff --git a/src/coulobre/settings.py b/src/coulobre/settings.py index 410978a..d03bf4f 100644 --- a/src/coulobre/settings.py +++ b/src/coulobre/settings.py @@ -119,6 +119,7 @@ CELERY_BROKER_TRANSPORT_OPTIONS = {"confirm_publish": True} CELERY_TASK_DEFAULT_QUEUE = "coulobre" CELERY_TASK_IGNORE_RESULT = True LOCAL_WEB_ACTIVATION = os.environ.get("COULOBRE_LOCAL_WEB_ACTIVATION") == "1" +LOCAL_WEB_HTTPS = os.environ.get("COULOBRE_LOCAL_WEB_HTTPS") == "1" LOCAL_DATABASE_PROVISIONING = ( os.environ.get("COULOBRE_LOCAL_DATABASE_PROVISIONING") == "1" ) @@ -139,6 +140,12 @@ if LOCAL_WEB_ACTIVATION: "schedule": 5.0, "options": {"expires": 4.0}, } +if LOCAL_WEB_HTTPS: + CELERY_BEAT_SCHEDULE["dispatch-web-https"] = { + "task": "coulobre.hosting.tasks.dispatch_web_https", + "schedule": 5.0, + "options": {"expires": 4.0}, + } if LOCAL_DATABASE_PROVISIONING: CELERY_BEAT_SCHEDULE["dispatch-database-provisioning"] = { "task": "coulobre.hosting.tasks.dispatch_database_provisioning", -- 2.43.0