Provision website HTTPS through a restricted Unix socket

This commit is contained in:
parkel committed 2026-11-21 10:30:36 +01:00
1 parent 145901cd84
commit 43d03d207e
6 files changed
+214 -9

No files matched your search

@@ -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
@@ -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
+23 -2
View File
@@ -50,13 +50,13 @@ class WebActivationRequestTests(SimpleTestCase):
patch("coulobre.web_node_apply.apply_site") patch("coulobre.web_node_apply.apply_site")
) )
def request(self, data): def request(self, data, *, command="apply-request"):
output = StringIO() output = StringIO()
with ( with (
patch("sys.stdin", SimpleNamespace(buffer=BytesIO(data))), patch("sys.stdin", SimpleNamespace(buffer=BytesIO(data))),
redirect_stdout(output), redirect_stdout(output),
): ):
code = main(["apply-request"]) code = main([command])
return code, json.loads(output.getvalue()) return code, json.loads(output.getvalue())
def test_replies_with_the_identity_of_the_applied_manifest(self): 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.", "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()
+67 -1
View File
@@ -1,4 +1,5 @@
from pathlib import Path from pathlib import Path
from subprocess import DEVNULL, CalledProcessError
from tempfile import TemporaryDirectory from tempfile import TemporaryDirectory
from unittest.mock import call, patch 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 import WebSite
from coulobre.web_node_apply import SitePaths 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): class WebNodeTLSTests(SimpleTestCase):
@@ -47,6 +53,12 @@ class WebNodeTLSTests(SimpleTestCase):
patch("coulobre.web_node_tls.STATE_DIRECTORY", self.state) 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.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( self.enterContext(
patch( patch(
"coulobre.web_node_tls.SitePaths.for_site", return_value=paths "coulobre.web_node_tls.SitePaths.for_site", return_value=paths
@@ -169,3 +181,57 @@ class WebNodeTLSTests(SimpleTestCase):
self.assertEqual(report["state"], "needs_attention") self.assertEqual(report["state"], "needs_attention")
self.assertIn("Existing configuration differs", report["problem"]) self.assertIn("Existing configuration differs", report["problem"])
self.assertEqual(self.tls.read_text(), "changed") 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))
+11
View File
@@ -100,6 +100,10 @@ def main(argv=None):
help="Enable HTTPS with an existing Certbot certificate.", help="Enable HTTPS with an existing Certbot certificate.",
) )
https.add_argument("manifest", type=Path) 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 = commands.add_parser(
"https-status", help="Check a site's local HTTPS configuration." "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 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: try:
payload = json.loads(args.manifest.read_text(encoding="utf-8")) payload = json.loads(args.manifest.read_text(encoding="utf-8"))
site = WebSite.from_manifest(payload) site = WebSite.from_manifest(payload)
+79 -6
View File
@@ -1,6 +1,7 @@
import fcntl import fcntl
import os import os
import ssl import ssl
import subprocess
from contextlib import contextmanager from contextlib import contextmanager
from pathlib import Path from pathlib import Path
@@ -19,6 +20,70 @@ from .web_node_apply import (
) )
CERTBOT_ROOT = Path("/etc/letsencrypt") 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): def enable_https(site):
@@ -28,10 +93,7 @@ def enable_https(site):
paths = SitePaths.for_site(site) paths = SitePaths.for_site(site)
apache, enabled = https_paths(paths) apache, enabled = https_paths(paths)
with locked_web_node(fcntl.LOCK_EX): with locked_web_node(fcntl.LOCK_EX):
check_reservation(site) check_https_prerequisites(site, paths)
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) config = https_configuration(site)
with configuration_installation() as (created, reload_attempts): with configuration_installation() as (created, reload_attempts):
install_configuration(apache, config, created) install_configuration(apache, config, created)
@@ -41,6 +103,13 @@ def enable_https(site):
run("/usr/sbin/service", "apache2", "reload") 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): def https_status(site):
if os.geteuid() != 0: if os.geteuid() != 0:
raise ValueError("Run https-status as root on the web node.") 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) 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): def https_configuration(site):
name = f"coulobre-{site.account_id}" lineage = certbot_lineage(site)
lineage = CERTBOT_ROOT / "live" / name name = lineage.name
archive = CERTBOT_ROOT / "archive" / name archive = CERTBOT_ROOT / "archive" / name
for directory in (lineage, archive): for directory in (lineage, archive):
try: try: