From 62df077225ca3295640c933c0d03fc92b94985bd Mon Sep 17 00:00:00 2001 From: Peter van Arkel Date: Sat, 21 Nov 2026 02:41:40 +0100 Subject: [PATCH 1/2] Enable HTTPS for hosted sites with Certbot certificates --- .../templates/hosting/apache-vhost.conf | 4 +- src/coulobre/hosting/test_web_node_tls.py | 171 ++++++++++++++++++ src/coulobre/node_files.py | 6 +- src/coulobre/web_node.py | 24 ++- src/coulobre/web_node_apply.py | 47 +++-- src/coulobre/web_node_tls.py | 141 +++++++++++++++ 6 files changed, 371 insertions(+), 22 deletions(-) create mode 100644 src/coulobre/hosting/test_web_node_tls.py create mode 100644 src/coulobre/web_node_tls.py diff --git a/src/coulobre/hosting/templates/hosting/apache-vhost.conf b/src/coulobre/hosting/templates/hosting/apache-vhost.conf index 3098aee..70bef32 100644 --- a/src/coulobre/hosting/templates/hosting/apache-vhost.conf +++ b/src/coulobre/hosting/templates/hosting/apache-vhost.conf @@ -1,7 +1,7 @@ - + ServerName $domain DocumentRoot "$document_root" - +$tls_settings AllowOverride None Options None diff --git a/src/coulobre/hosting/test_web_node_tls.py b/src/coulobre/hosting/test_web_node_tls.py new file mode 100644 index 0000000..cd8ad73 --- /dev/null +++ b/src/coulobre/hosting/test_web_node_tls.py @@ -0,0 +1,171 @@ +from pathlib import Path +from tempfile import TemporaryDirectory +from unittest.mock import call, patch + +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 + + +class WebNodeTLSTests(SimpleTestCase): + def setUp(self): + directory = Path(self.enterContext(TemporaryDirectory())) + self.site = WebSite(42, "example.org") + self.state = directory / "state" + self.state.mkdir() + (self.state / "apply.lock").touch() + self.http = directory / "sites-available" / "coulobre-42.conf" + http_enabled = directory / "sites-enabled" / self.http.name + for path in (self.http, http_enabled): + path.parent.mkdir() + self.http.write_text(self.site.render("apache"), encoding="utf-8") + self.tls = self.http.with_name("coulobre-42-https.conf") + self.enabled = http_enabled.with_name(self.tls.name) + paths = SitePaths( + directory / "account", + self.http, + http_enabled, + directory / "php.conf", + directory / "site.sock", + ) + certbot = directory / "letsencrypt" + self.live = certbot / "live" / "coulobre-42" + self.archive = certbot / "archive" / "coulobre-42" + for path in (self.live, self.archive): + path.mkdir(parents=True) + for name in ("fullchain", "privkey"): + target = self.archive / f"{name}1.pem" + target.touch() + (self.live / f"{name}.pem").symlink_to(target) + + self.enterContext( + patch("coulobre.web_node_tls.os.geteuid", return_value=0) + ) + self.enterContext( + patch("coulobre.web_node_tls.STATE_DIRECTORY", self.state) + ) + self.enterContext(patch("coulobre.web_node_tls.CERTBOT_ROOT", certbot)) + self.enterContext( + patch( + "coulobre.web_node_tls.SitePaths.for_site", return_value=paths + ) + ) + self.enterContext( + patch( + "coulobre.web_node_tls.require_root_directory", + side_effect=self.require_fixture_directory, + ) + ) + self.enterContext( + patch( + "coulobre.web_node_apply.read_root_file", + side_effect=Path.read_text, + ) + ) + self.files = self.enterContext( + patch("coulobre.web_node_tls.check_root_file") + ) + self.reservation = self.enterContext( + patch("coulobre.web_node_tls.check_reservation") + ) + self.enterContext(patch("coulobre.web_node_tls.check_installation")) + self.ssl = self.enterContext( + patch("coulobre.web_node_tls.ssl.SSLContext") + ) + self.runner = self.enterContext( + patch("coulobre.web_node_tls.run", return_value=" ssl_module") + ) + self.recovery = self.enterContext(patch("coulobre.web_node_apply.run")) + + @staticmethod + def require_fixture_directory(path): + if not path.is_dir(): + raise FileNotFoundError(path) + + def test_enables_https_alongside_the_existing_http_site(self): + previous = self.http.read_text() + enable_https(self.site) + enable_https(self.site) + + self.assertEqual(self.http.read_text(), previous) + self.assertEqual(self.enabled.resolve(), self.tls) + content = self.tls.read_text() + self.assertIn("", content) + self.assertIn('DocumentRoot "/srv/coulobre/web/42/public"', content) + self.assertIn("proxy:unix:/run/php/coulobre-42.sock", content) + self.assertIn( + f'SSLCertificateFile "{self.live}/fullchain.pem"', content + ) + self.assertIn( + f'SSLCertificateKeyFile "{self.live}/privkey.pem"', content + ) + self.files.assert_any_call(self.archive / "privkey1.pem", mode=0o600) + self.ssl.return_value.load_cert_chain.assert_called_with( + self.archive / "fullchain1.pem", + self.archive / "privkey1.pem", + password="", + ) + self.runner.assert_any_call( + "/usr/bin/openssl", + "verify", + "-trusted", + str(self.archive / "fullchain1.pem"), + "-partial_chain", + "-purpose", + "sslserver", + "-verify_hostname", + "example.org", + str(self.archive / "fullchain1.pem"), + ) + self.assertEqual( + self.runner.call_args_list[-2:], + [ + call("/usr/sbin/apache2ctl", "configtest"), + call("/usr/sbin/service", "apache2", "reload"), + ], + ) + + def test_rejects_lineage_links_outside_the_account_archive(self): + private_key = self.live / "privkey.pem" + private_key.unlink() + foreign = self.archive.parent / "foreign-key.pem" + foreign.touch() + private_key.symlink_to(foreign) + + with self.assertRaisesMessage(ValueError, "to point into"): + enable_https(self.site) + + self.assertFalse(self.tls.exists()) + self.ssl.assert_not_called() + + def test_failed_reload_removes_https_files_and_restores_apache(self): + def command(*args): + if args[-1] == "reload": + raise ValueError("Reload failed.") + return " ssl_module" + + self.runner.side_effect = command + with self.assertRaisesMessage(ValueError, "Reload failed."): + enable_https(self.site) + + self.assertTrue(self.http.exists()) + self.assertFalse(self.tls.exists()) + self.assertFalse(self.enabled.is_symlink()) + self.recovery.assert_called_once_with( + "/usr/sbin/service", "apache2", "reload" + ) + + def test_status_reports_absence_and_drift_without_rewriting_files(self): + self.assertEqual(https_status(self.site)["state"], "not_installed") + self.reservation.assert_not_called() + enable_https(self.site) + self.assertEqual(https_status(self.site)["state"], "configured") + + self.tls.write_text("changed", encoding="utf-8") + report = https_status(self.site) + + self.assertEqual(report["state"], "needs_attention") + self.assertIn("Existing configuration differs", report["problem"]) + self.assertEqual(self.tls.read_text(), "changed") diff --git a/src/coulobre/node_files.py b/src/coulobre/node_files.py index 0f20e68..e3ddfef 100644 --- a/src/coulobre/node_files.py +++ b/src/coulobre/node_files.py @@ -22,6 +22,11 @@ def check_root_directory(path): def read_root_file(path, *, mode=None): + check_root_file(path, mode=mode) + return path.read_text(encoding="utf-8") + + +def check_root_file(path, *, mode=None): info = path.lstat() if ( not stat.S_ISREG(info.st_mode) @@ -31,7 +36,6 @@ def read_root_file(path, *, mode=None): raise ValueError(f"Expected a root-controlled file at {path}.") if mode is not None and stat.S_IMODE(info.st_mode) != mode: raise ValueError(f"Expected permissions {mode:04o} on {path}.") - return path.read_text(encoding="utf-8") def write_new_file(path, content, *, mode, group=None): diff --git a/src/coulobre/web_node.py b/src/coulobre/web_node.py index 5f57885..4b42ecd 100644 --- a/src/coulobre/web_node.py +++ b/src/coulobre/web_node.py @@ -66,12 +66,12 @@ class WebSite: "socket_path": f"/run/php/{service_user}.sock", } - def render(self, configuration): + def render(self, configuration, *, port=80, tls_settings=""): resource = files("coulobre.hosting").joinpath( "templates", "hosting", CONFIGURATIONS[configuration] ) return Template(resource.read_text(encoding="utf-8")).substitute( - self.configuration() + self.configuration(), port=port, tls_settings=tls_settings ) @@ -95,6 +95,15 @@ def main(argv=None): "status", help="Check a site's local configuration and services." ) status.add_argument("manifest", type=Path) + https = commands.add_parser( + "enable-https", + help="Enable HTTPS with an existing Certbot certificate.", + ) + https.add_argument("manifest", type=Path) + https_status = commands.add_parser( + "https-status", help="Check a site's local HTTPS configuration." + ) + https_status.add_argument("manifest", type=Path) restore = commands.add_parser( "restore-directadmin", help="Restore a DirectAdmin website into an empty web root.", @@ -127,6 +136,17 @@ def main(argv=None): report = site_status(site) print(json.dumps(report, indent=2)) return 0 if report["state"] == "configured" else 2 + elif args.command == "enable-https": + from .web_node_tls import enable_https + + enable_https(site) + print(f"Enabled HTTPS for {site.domain}.") + elif args.command == "https-status": + from .web_node_tls import https_status + + report = https_status(site) + print(json.dumps(report, indent=2)) + return 0 if report["state"] == "configured" else 2 elif args.command == "restore-directadmin": from .web_node_restore import restore_website diff --git a/src/coulobre/web_node_apply.py b/src/coulobre/web_node_apply.py index 7a04fd1..760abc3 100644 --- a/src/coulobre/web_node_apply.py +++ b/src/coulobre/web_node_apply.py @@ -6,6 +6,7 @@ import pwd import stat import subprocess import time +from contextlib import contextmanager from dataclasses import dataclass from pathlib import Path @@ -261,23 +262,10 @@ def check_public_directory(path, uid, gid): def install_configurations(site, apache, enabled, pool, socket): - created = [] - reload_attempts = [] - try: - for path, name in ((apache, "apache"), (pool, "php-fpm")): - content = site.render(name) - if os.path.lexists(path): - check_configuration(path, content) - else: - write_new_file(path, content, mode=0o644) - created.append(path) - - link_target = Path("../sites-available") / apache.name - if os.path.lexists(enabled): - check_site_link(enabled, link_target) - else: - enabled.symlink_to(link_target) - created.append(enabled) + with configuration_installation() as (created, reload_attempts): + install_configuration(apache, site.render("apache"), created) + install_configuration(pool, site.render("php-fpm"), created) + enable_apache_site(apache, enabled, created) run("/usr/sbin/php-fpm8.5", "--test") run("/usr/sbin/apache2ctl", "configtest") @@ -286,6 +274,31 @@ def install_configurations(site, apache, enabled, pool, socket): wait_for_socket(socket) reload_attempts.append("apache2") run("/usr/sbin/service", "apache2", "reload") + + +def install_configuration(path, content, created): + if os.path.lexists(path): + check_configuration(path, content) + else: + write_new_file(path, content, mode=0o644) + created.append(path) + + +def enable_apache_site(apache, enabled, created): + link_target = Path("../sites-available") / apache.name + if os.path.lexists(enabled): + check_site_link(enabled, link_target) + else: + enabled.symlink_to(link_target) + created.append(enabled) + + +@contextmanager +def configuration_installation(): + created = [] + reload_attempts = [] + try: + yield created, reload_attempts except (OSError, ValueError, KeyboardInterrupt) as error: failures = [] for path in reversed(created): diff --git a/src/coulobre/web_node_tls.py b/src/coulobre/web_node_tls.py new file mode 100644 index 0000000..3ec8204 --- /dev/null +++ b/src/coulobre/web_node_tls.py @@ -0,0 +1,141 @@ +import fcntl +import os +import ssl +from contextlib import contextmanager +from pathlib import Path + +from .node_files import check_root_file, require_root_directory +from .web_node_apply import ( + STATE_DIRECTORY, + SitePaths, + check_configuration, + check_installation, + check_reservation, + check_site_link, + configuration_installation, + enable_apache_site, + install_configuration, + run, +) + +CERTBOT_ROOT = Path("/etc/letsencrypt") + + +def enable_https(site): + if os.geteuid() != 0: + raise ValueError("Run enable-https as root on the web node.") + + 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.") + config = https_configuration(site) + with configuration_installation() as (created, reload_attempts): + install_configuration(apache, config, created) + enable_apache_site(apache, enabled, created) + run("/usr/sbin/apache2ctl", "configtest") + reload_attempts.append("apache2") + run("/usr/sbin/service", "apache2", "reload") + + +def https_status(site): + if os.geteuid() != 0: + raise ValueError("Run https-status as root on the web node.") + + report = {**site.manifest(), "state": "not_installed", "problem": None} + paths = SitePaths.for_site(site) + apache, enabled = https_paths(paths) + try: + for directory in (apache.parent, enabled.parent): + require_root_directory(directory) + if not (os.path.lexists(apache) or os.path.lexists(enabled)): + return report + with locked_web_node(fcntl.LOCK_SH): + check_reservation(site) + check_installation(site, paths) + check_configuration(apache, https_configuration(site)) + check_site_link(enabled, Path("../sites-available") / apache.name) + run("/usr/sbin/apache2ctl", "configtest") + except (OSError, ValueError) as error: + return {**report, "state": "needs_attention", "problem": str(error)} + return {**report, "state": "configured"} + + +@contextmanager +def locked_web_node(mode): + try: + require_root_directory(STATE_DIRECTORY) + except FileNotFoundError: + raise ValueError( + "Apply the site manifest before enabling HTTPS." + ) from None + lock_path = STATE_DIRECTORY / "apply.lock" + check_root_file(lock_path) + with lock_path.open("r") as lock: + fcntl.flock(lock, mode) + yield + + +def https_paths(paths): + name = f"{paths.apache.stem}-https.conf" + return paths.apache.with_name(name), paths.enabled.with_name(name) + + +def https_configuration(site): + name = f"coulobre-{site.account_id}" + lineage = CERTBOT_ROOT / "live" / name + archive = CERTBOT_ROOT / "archive" / name + for directory in (lineage, archive): + try: + require_root_directory(directory) + except FileNotFoundError: + raise ValueError( + f"Obtain the Certbot certificate named {name}." + ) from None + + certificate = lineage / "fullchain.pem" + private_key = lineage / "privkey.pem" + resolved = [] + for source in (certificate, private_key): + target = source.resolve(strict=True) + if target.parent != archive: + raise ValueError(f"Expected {source} to point into {archive}.") + resolved.append(target) + chain_file, key_file = resolved + check_root_file(chain_file) + check_root_file(key_file, mode=0o600) + try: + ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER).load_cert_chain( + chain_file, key_file, password="" + ) + except ssl.SSLError: + raise ValueError( + "Could not load the Certbot certificate and private key." + ) from None + run( + "/usr/bin/openssl", + "verify", + "-trusted", + str(chain_file), + "-partial_chain", + "-purpose", + "sslserver", + "-verify_hostname", + site.domain, + str(chain_file), + ) + + return site.render( + "apache", + port=443, + tls_settings=( + "\n" + " SSLEngine On\n" + " SSLProtocol -all +TLSv1.2 +TLSv1.3\n" + f' SSLCertificateFile "{certificate}"\n' + f' SSLCertificateKeyFile "{private_key}"\n' + ), + ) -- 2.43.0 From 3be2f8fd0709d627f1b089dcdd508b6ac410dc22 Mon Sep 17 00:00:00 2001 From: Peter van Arkel Date: Sat, 21 Nov 2026 02:43:29 +0100 Subject: [PATCH 2/2] Add Certbot webroot setup and Apache renewal hook --- .gitea/workflows/ci.yml | 1 + deploy/apache/acme.conf.example | 7 ++++ deploy/certbot/reload-apache.sh | 14 ++++++++ docs/deployment.md | 7 ++++ docs/development.md | 58 +++++++++++++++++++++++++++++++++ 5 files changed, 87 insertions(+) create mode 100644 deploy/apache/acme.conf.example create mode 100755 deploy/certbot/reload-apache.sh diff --git a/.gitea/workflows/ci.yml b/.gitea/workflows/ci.yml index 1bf9ee7..86d0ab4 100644 --- a/.gitea/workflows/ci.yml +++ b/.gitea/workflows/ci.yml @@ -43,6 +43,7 @@ jobs: ruff check . ruff format --check . sh -n tests/web-node/smoke.sh + sh -n deploy/certbot/reload-apache.sh - name: Check Django configuration and migrations run: | diff --git a/deploy/apache/acme.conf.example b/deploy/apache/acme.conf.example new file mode 100644 index 0000000..eeb05df --- /dev/null +++ b/deploy/apache/acme.conf.example @@ -0,0 +1,7 @@ +Alias "/.well-known/acme-challenge/" "/var/www/coulobre-acme/.well-known/acme-challenge/" + + + AllowOverride None + Options None + Require all granted + diff --git a/deploy/certbot/reload-apache.sh b/deploy/certbot/reload-apache.sh new file mode 100755 index 0000000..77ff5d8 --- /dev/null +++ b/deploy/certbot/reload-apache.sh @@ -0,0 +1,14 @@ +#!/bin/sh +set -eu + +case "${RENEWED_LINEAGE:-}" in + /etc/letsencrypt/live/coulobre-*) + lock=/var/lib/coulobre/web-node/apply.lock + if [ -f "$lock" ]; then + exec 9<"$lock" + flock -x 9 + /usr/sbin/apache2ctl configtest 2>&1 + /usr/sbin/service apache2 reload + fi + ;; +esac diff --git a/docs/deployment.md b/docs/deployment.md index 3a7b10c..a5a2930 100644 --- a/docs/deployment.md +++ b/docs/deployment.md @@ -212,6 +212,13 @@ The worker applies the domain shown in the preview. If the account's primary domain changes before the worker starts, create a preview for the new domain. An existing web node reservation stays bound to the domain it was created for. +## Enable HTTPS for hosted websites + +Once a site is active, obtain the website certificate with Certbot on the +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) + ## 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 d6288c7..3299dde 100644 --- a/docs/development.md +++ b/docs/development.md @@ -670,6 +670,63 @@ The status command reads local state. It exits with code 0 for `configured`, code 2 for the other report states, and code 1 if it cannot read the manifest or inspect the node. Use an HTTP request to verify the site's response as well. +### Enable HTTPS for a hosted website + +Apply the web deployment manifest first. Use Certbot to obtain and renew +the website's Let's Encrypt certificate. The HTTP-01 challenge requires +public DNS for the domain and an inbound connection on port 80. If a +reverse proxy handles that port, forward `/.well-known/acme-challenge/` +for the domain to the web node, preserving the host and path. +[Let's Encrypt challenge types](https://letsencrypt.org/docs/challenge-types/) + +Prepare Apache and the shared challenge directory once per web node. +Apache serves challenge files from this directory, which the web node +operator controls. + +```sh +sudo apt install certbot +sudo a2enmod ssl +sudo install -d -m 0755 /var/www/coulobre-acme/.well-known/acme-challenge +sudo install -m 0644 deploy/apache/acme.conf.example \ + /etc/apache2/conf-available/coulobre-acme.conf +sudo a2enconf coulobre-acme +sudo apache2ctl configtest +sudo systemctl reload apache2 +``` + +Use the manifest's account ID for the Certbot certificate name and its +primary domain for the certificate hostname. Keep Certbot's private key +root-owned with mode `0600`. Apache uses the managed Certbot lineage on +port 443, with the same document root and PHP-FPM pool as the HTTP site. + +```sh +sudo certbot certonly --webroot --webroot-path /var/www/coulobre-acme \ + --cert-name coulobre-1 --domains example.org +sudo /opt/coulobre/bin/coulobre-web-node enable-https coulobre-web-plan-1.json +sudo /opt/coulobre/bin/coulobre-web-node https-status coulobre-web-plan-1.json +curl --fail https://example.org/ +``` + +`https-status` checks the local virtual host and certificate on disk. +An HTTPS request verifies the certificate and response clients receive. +HTTP remains available for the site and future HTTP-01 challenges. + +Install the renewal hook and check the Certbot timer. After a successful +renewal of a Coulobre certificate, the hook validates the Apache +configuration and reloads the service. + +```sh +sudo install -D -m 0755 deploy/certbot/reload-apache.sh \ + /etc/letsencrypt/renewal-hooks/deploy/coulobre-apache +systemctl status certbot.timer +sudo certbot renew --dry-run --run-deploy-hooks --cert-name coulobre-1 +``` + +For a public domain that cannot accept inbound HTTP on port 80, Certbot +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) + ### Enable local web activation On a web node with the same Apache and PHP-FPM setup, systemd can accept local @@ -741,6 +798,7 @@ fixtures. Then run the checks from the repository root. ruff check . ruff format --check . sh -n tests/web-node/smoke.sh +sh -n deploy/certbot/reload-apache.sh python manage.py check python manage.py makemigrations --check --dry-run python manage.py test coulobre -- 2.43.0