From 43d03d207ebcbdf6ce52f6e6754c711dea4b9d97 Mon Sep 17 00:00:00 2001 From: Peter van Arkel Date: Sat, 21 Nov 2026 10:30:36 +0100 Subject: [PATCH] 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: