From aea049087d949debcd7fce59d20fdb32eb85413f Mon Sep 17 00:00:00 2001 From: Peter van Arkel Date: Thu, 19 Nov 2026 21:44:15 +0100 Subject: [PATCH 1/3] Add a versioned web-node deployment manifest Export the account ID and domain from a completed preview. Render matching Apache and PHP-FPM configuration on the web node. --- CONTRIBUTING.md | 2 - docs/development.md | 19 +++++ pyproject.toml | 3 + src/coulobre/domain_names.py | 16 ++++ src/coulobre/hosting/fields.py | 12 +-- src/coulobre/hosting/tasks.py | 8 +- .../templates/hosting/apache-vhost.conf | 10 +-- .../templates/hosting/php-fpm-pool.conf | 8 +- .../templates/hosting/plan_detail.html | 5 +- src/coulobre/hosting/test_web_node.py | 32 +++++++ .../hosting/test_web_node_manifest.py | 34 ++++++++ src/coulobre/hosting/urls.py | 7 +- src/coulobre/hosting/views.py | 22 +++-- src/coulobre/hosting/web_node.py | 20 ++--- src/coulobre/web_node.py | 85 +++++++++++++++++++ 15 files changed, 239 insertions(+), 44 deletions(-) create mode 100644 src/coulobre/domain_names.py create mode 100644 src/coulobre/hosting/test_web_node_manifest.py create mode 100644 src/coulobre/web_node.py diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index d00ab45..7167387 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -2,8 +2,6 @@ - Use Gitea issues for work items and milestones for release planning. - Start changes on a dedicated branch from the default branch, named main. -- Keep related commits on the same branch and open one pull request when they - form a coherent change that can be reviewed and verified together. - Reference the relevant issue in the pull request and describe what changed and how it was verified. - Submit changes for review before merging into main. diff --git a/docs/development.md b/docs/development.md index c154fc9..38615bb 100644 --- a/docs/development.md +++ b/docs/development.md @@ -48,6 +48,25 @@ to RabbitMQ. After a broker outage, queued requests resume when the worker and scheduler reconnect. Plans that remain incomplete five minutes after dispatch are eligible for delivery again. +## Render configuration on a web node + +Open a completed preview for the account's current domain and select **Download +deployment manifest**. The versioned JSON file contains the account ID and +primary domain. The web node command validates those values and derives the +system user, document root, and PHP-FPM socket from the account ID. + +Install the panel package on the node at the same revision as the panel that +created the manifest. The command renders configuration to standard output. +Run it as a regular user in a directory for reviewing the generated files. + +```sh +coulobre-web-node render coulobre-web-plan-1.json apache > apache.conf +coulobre-web-node render coulobre-web-plan-1.json php-fpm > php-fpm.conf +``` + +The command reads the manifest and packaged templates locally. The isolated +Ubuntu check below demonstrates loading the configuration. + ## Run an isolated PHP test site Open a completed preview for the account's current domain and select **Download diff --git a/pyproject.toml b/pyproject.toml index a7366e3..77c8fcc 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -15,6 +15,9 @@ dependencies = [ "idna>=3,<4", ] +[project.scripts] +coulobre-web-node = "coulobre.web_node:main" + [project.optional-dependencies] dev = ["ruff>=0.11,<1"] mariadb = ["mysqlclient>=2.2.1,<3"] diff --git a/src/coulobre/domain_names.py b/src/coulobre/domain_names.py new file mode 100644 index 0000000..3d122d8 --- /dev/null +++ b/src/coulobre/domain_names.py @@ -0,0 +1,16 @@ +import idna +from django.core.exceptions import ValidationError +from django.core.validators import DomainNameValidator + +validate_domain = DomainNameValidator(accept_idna=False) + + +def canonical_domain(value): + try: + domain = ( + idna.encode(value.strip(), uts46=True).decode("ascii").removesuffix(".") + ) + validate_domain(domain) + except (idna.IDNAError, ValidationError) as error: + raise ValueError("Enter a valid domain name.") from error + return domain diff --git a/src/coulobre/hosting/fields.py b/src/coulobre/hosting/fields.py index 7b63e5f..7c144c8 100644 --- a/src/coulobre/hosting/fields.py +++ b/src/coulobre/hosting/fields.py @@ -1,9 +1,7 @@ -import idna from django.core.exceptions import ValidationError -from django.core.validators import DomainNameValidator from django.db import models -validate_domain = DomainNameValidator(accept_idna=False) +from coulobre.domain_names import canonical_domain, validate_domain class DomainNameField(models.CharField): @@ -15,10 +13,6 @@ class DomainNameField(models.CharField): return value try: - domain = idna.encode(value.strip(), uts46=True).decode("ascii") - except idna.IDNAError as error: + return canonical_domain(value) + except ValueError as error: raise ValidationError(validate_domain.message, code="invalid") from error - - domain = domain.removesuffix(".") - validate_domain(domain) - return domain diff --git a/src/coulobre/hosting/tasks.py b/src/coulobre/hosting/tasks.py index a403f47..fd4cf6b 100644 --- a/src/coulobre/hosting/tasks.py +++ b/src/coulobre/hosting/tasks.py @@ -2,11 +2,11 @@ from datetime import timedelta from celery import shared_task from django.db.models import Q -from django.template.loader import render_to_string from django.utils import timezone +from coulobre.web_node import WebSite + from .models import WebProvisioningPlan -from .web_node import web_site_configuration REDISPATCH_AFTER = timedelta(minutes=5) @@ -37,7 +37,5 @@ def render_web_plan(plan_id): if plan is None: return - apache_config = render_to_string( - "hosting/apache-vhost.conf", web_site_configuration(plan) - ) + apache_config = WebSite(plan.account_id, plan.primary_domain).render("apache") pending.update(apache_config=apache_config, completed_at=timezone.now()) diff --git a/src/coulobre/hosting/templates/hosting/apache-vhost.conf b/src/coulobre/hosting/templates/hosting/apache-vhost.conf index adeef4c..3098aee 100644 --- a/src/coulobre/hosting/templates/hosting/apache-vhost.conf +++ b/src/coulobre/hosting/templates/hosting/apache-vhost.conf @@ -1,14 +1,14 @@ - ServerName {{ domain }} - DocumentRoot "{{ document_root }}" + ServerName $domain + DocumentRoot "$document_root" - + AllowOverride None Options None Require all granted - - SetHandler "proxy:unix:{{ socket_path }}|fcgi://localhost/" + + SetHandler "proxy:unix:$socket_path|fcgi://localhost/" diff --git a/src/coulobre/hosting/templates/hosting/php-fpm-pool.conf b/src/coulobre/hosting/templates/hosting/php-fpm-pool.conf index 29127f9..63c2b08 100644 --- a/src/coulobre/hosting/templates/hosting/php-fpm-pool.conf +++ b/src/coulobre/hosting/templates/hosting/php-fpm-pool.conf @@ -1,7 +1,7 @@ -[{{ service_user }}] -user = {{ service_user }} -group = {{ service_user }} -listen = {{ socket_path }} +[$service_user] +user = $service_user +group = $service_user +listen = $socket_path listen.owner = www-data listen.group = www-data listen.mode = 0660 diff --git a/src/coulobre/hosting/templates/hosting/plan_detail.html b/src/coulobre/hosting/templates/hosting/plan_detail.html index b801c09..6978de0 100644 --- a/src/coulobre/hosting/templates/hosting/plan_detail.html +++ b/src/coulobre/hosting/templates/hosting/plan_detail.html @@ -24,7 +24,10 @@

Virtual host configuration

{% if plan.can_export %} - Download test bundle + {% endif %}
{{ plan.apache_config }}
diff --git a/src/coulobre/hosting/test_web_node.py b/src/coulobre/hosting/test_web_node.py index fbeb175..825c133 100644 --- a/src/coulobre/hosting/test_web_node.py +++ b/src/coulobre/hosting/test_web_node.py @@ -6,6 +6,8 @@ from django.contrib.auth import get_user_model from django.test import TestCase from django.urls import reverse +from coulobre.web_node import WebSite + from .models import HostingAccount, WebProvisioningPlan from .tasks import render_web_plan @@ -25,6 +27,9 @@ class WebSmokeBundleTests(TestCase): def setUp(self): self.client.force_login(self.operator) self.download = reverse("panel:download_smoke_bundle", args=[self.plan.pk]) + self.manifest = reverse( + "panel:download_deployment_manifest", args=[self.plan.pk] + ) def test_export_uses_the_reviewed_preview_and_matching_php_fpm_settings(self): render_web_plan.run(self.plan.pk) @@ -57,17 +62,44 @@ class WebSmokeBundleTests(TestCase): def test_pending_and_stale_previews_cannot_be_exported(self): self.assertEqual(self.client.get(self.download).status_code, 409) + self.assertEqual(self.client.get(self.manifest).status_code, 409) render_web_plan.run(self.plan.pk) HostingAccount.objects.filter(pk=self.account.pk).update( primary_domain="updated.example" ) self.assertEqual(self.client.get(self.download).status_code, 409) + self.assertEqual(self.client.get(self.manifest).status_code, 409) detail = self.client.get(reverse("panel:plan", args=[self.plan.pk])) self.assertNotContains(detail, "Download test bundle") + self.assertNotContains(detail, "Download deployment manifest") def test_download_requires_plan_view_permission(self): render_web_plan.run(self.plan.pk) self.client.force_login(self.viewer) self.assertEqual(self.client.get(self.download).status_code, 403) + self.assertEqual(self.client.get(self.manifest).status_code, 403) + + def test_manifest_reproduces_preview_and_pool_on_the_node(self): + render_web_plan.run(self.plan.pk) + + detail = self.client.get(reverse("panel:plan", args=[self.plan.pk])) + self.assertContains(detail, "Download deployment manifest") + response = self.client.get(self.manifest) + self.assertEqual(response.status_code, 200) + self.assertIn(".json", response["Content-Disposition"]) + self.assertEqual( + response.json(), + {"version": 1, "account_id": self.account.pk, "domain": "example.org"}, + ) + + self.plan.refresh_from_db() + site = WebSite.from_manifest(response.json()) + self.assertEqual(site.render("apache"), self.plan.apache_config) + bundle = self.client.get(self.download) + with tarfile.open(fileobj=BytesIO(bundle.content)) as archive: + self.assertEqual( + site.render("php-fpm"), + archive.extractfile("php-fpm.conf").read().decode(), + ) diff --git a/src/coulobre/hosting/test_web_node_manifest.py b/src/coulobre/hosting/test_web_node_manifest.py new file mode 100644 index 0000000..8722d75 --- /dev/null +++ b/src/coulobre/hosting/test_web_node_manifest.py @@ -0,0 +1,34 @@ +from django.test import SimpleTestCase + +from coulobre.web_node import WebSite + + +class WebSiteManifestTests(SimpleTestCase): + def test_manifest_derives_paths_and_canonicalizes_the_domain(self): + site = WebSite.from_manifest( + {"version": 1, "account_id": 42, "domain": "BÜCHER.example."} + ) + + self.assertEqual(site.manifest()["domain"], "xn--bcher-kva.example") + self.assertIn( + 'DocumentRoot "/srv/coulobre/web/42/public"', site.render("apache") + ) + self.assertIn('FilesMatch "\\.php$"', site.render("apache")) + self.assertIn("listen = /run/php/coulobre-42.sock", site.render("php-fpm")) + + def test_manifest_rejects_wrong_versions_and_untrusted_configuration(self): + manifest = {"version": 1, "account_id": 42, "domain": "example.org"} + invalid = ( + {"version": 2}, + {"version": True}, + {"account_id": True}, + {"account_id": -1}, + {"account_id": 2**63}, + {"account_id": "../../etc"}, + {"domain": "example.org\nServerAlias *"}, + {"domain": "localhost"}, + {"document_root": "/tmp"}, + ) + for change in invalid: + with self.subTest(change=change), self.assertRaises(ValueError): + WebSite.from_manifest(manifest | change) diff --git a/src/coulobre/hosting/urls.py b/src/coulobre/hosting/urls.py index f4a313a..71f798b 100644 --- a/src/coulobre/hosting/urls.py +++ b/src/coulobre/hosting/urls.py @@ -26,7 +26,12 @@ urlpatterns = [ path("plans//", views.PlanDetail.as_view(), name="plan"), path( "plans//smoke-bundle/", - views.DownloadWebSmokeBundle.as_view(), + views.DownloadWebPlan.as_view(), name="download_smoke_bundle", ), + path( + "plans//deployment-manifest/", + views.DownloadWebPlan.as_view(manifest=True), + name="download_deployment_manifest", + ), ] diff --git a/src/coulobre/hosting/views.py b/src/coulobre/hosting/views.py index 2c018ff..8337bb0 100644 --- a/src/coulobre/hosting/views.py +++ b/src/coulobre/hosting/views.py @@ -7,7 +7,7 @@ from django.views.generic import CreateView, DetailView, ListView, UpdateView from django.views.generic.detail import SingleObjectMixin from .models import HostingAccount, WebProvisioningPlan -from .web_node import build_web_smoke_bundle +from .web_node import build_web_smoke_bundle, serialize_deployment_manifest VIEW_ACCOUNTS = "hosting.view_hostingaccount" CHANGE_ACCOUNTS = "hosting.change_hostingaccount" @@ -97,7 +97,9 @@ class PlanDetail(PermissionRequiredMixin, DetailView): context_object_name = "plan" -class DownloadWebSmokeBundle(PlanDetail): +class DownloadWebPlan(PlanDetail): + manifest = False + def render_to_response(self, context, **response_kwargs): plan = self.object if not plan.can_export: @@ -107,11 +109,21 @@ class DownloadWebSmokeBundle(PlanDetail): content_type="text/plain", ) + if self.manifest: + content = serialize_deployment_manifest(plan) + extension = "json" + content_type = "application/json" + else: + content = build_web_smoke_bundle(plan) + extension = "tar" + content_type = "application/x-tar" return HttpResponse( - build_web_smoke_bundle(plan), - content_type="application/x-tar", + content, + content_type=content_type, headers={ "Cache-Control": "private, no-store", - "Content-Disposition": f'attachment; filename="coulobre-web-plan-{plan.pk}.tar"', + "Content-Disposition": ( + f'attachment; filename="coulobre-web-plan-{plan.pk}.{extension}"' + ), }, ) diff --git a/src/coulobre/hosting/web_node.py b/src/coulobre/hosting/web_node.py index d31c4a3..4fae3d9 100644 --- a/src/coulobre/hosting/web_node.py +++ b/src/coulobre/hosting/web_node.py @@ -4,24 +4,20 @@ from io import BytesIO from django.template.loader import render_to_string +from coulobre.web_node import WebSite -def web_site_configuration(plan): - service_user = f"coulobre-{plan.account_id}" - return { - "account_id": plan.account_id, - "domain": plan.primary_domain, - "service_user": service_user, - "document_root": f"/srv/coulobre/web/{plan.account_id}/public", - "socket_path": f"/run/php/{service_user}.sock", - } + +def serialize_deployment_manifest(plan): + site = WebSite(plan.account_id, plan.primary_domain) + return json.dumps(site.manifest(), indent=2) + "\n" def build_web_smoke_bundle(plan): - configuration = web_site_configuration(plan) + site = WebSite(plan.account_id, plan.primary_domain) files = { - "site.json": json.dumps(configuration, indent=2) + "\n", + "site.json": json.dumps(site.configuration(), indent=2) + "\n", "apache.conf": plan.apache_config, - "php-fpm.conf": render_to_string("hosting/php-fpm-pool.conf", configuration), + "php-fpm.conf": site.render("php-fpm"), "public/index.php": render_to_string("hosting/smoke-index.php"), } diff --git a/src/coulobre/web_node.py b/src/coulobre/web_node.py new file mode 100644 index 0000000..40951a9 --- /dev/null +++ b/src/coulobre/web_node.py @@ -0,0 +1,85 @@ +import argparse +import json +import sys +from dataclasses import dataclass +from importlib.resources import files +from pathlib import Path +from string import Template + +from .domain_names import canonical_domain + +MANIFEST_VERSION = 1 +CONFIGURATIONS = {"apache": "apache-vhost.conf", "php-fpm": "php-fpm-pool.conf"} + + +@dataclass(frozen=True) +class WebSite: + account_id: int + domain: str + + def __post_init__(self): + if type(self.account_id) is not int or not 1 <= self.account_id <= 2**63 - 1: + raise ValueError("The account ID must be a positive 64-bit integer.") + if not isinstance(self.domain, str): + raise ValueError("The domain must be a string.") + object.__setattr__(self, "domain", canonical_domain(self.domain)) + + @classmethod + def from_manifest(cls, data): + if not isinstance(data, dict) or data.keys() != { + "version", + "account_id", + "domain", + }: + raise ValueError( + "Expected a manifest with version, account_id, and domain." + ) + version = data["version"] + if type(version) is not int or version != MANIFEST_VERSION: + raise ValueError("Unsupported web deployment manifest version.") + return cls(data["account_id"], data["domain"]) + + def manifest(self): + return { + "version": MANIFEST_VERSION, + "account_id": self.account_id, + "domain": self.domain, + } + + def configuration(self): + service_user = f"coulobre-{self.account_id}" + return { + "account_id": self.account_id, + "domain": self.domain, + "service_user": service_user, + "document_root": f"/srv/coulobre/web/{self.account_id}/public", + "socket_path": f"/run/php/{service_user}.sock", + } + + def render(self, configuration): + resource = files("coulobre.hosting").joinpath( + "templates", "hosting", CONFIGURATIONS[configuration] + ) + return Template(resource.read_text(encoding="utf-8")).substitute( + self.configuration() + ) + + +def main(argv=None): + parser = argparse.ArgumentParser(prog="coulobre-web-node") + commands = parser.add_subparsers(dest="command", required=True) + render = commands.add_parser( + "render", help="Render configuration from a site manifest." + ) + render.add_argument("manifest", type=Path) + render.add_argument("configuration", choices=CONFIGURATIONS) + args = parser.parse_args(argv) + + try: + payload = json.loads(args.manifest.read_text(encoding="utf-8")) + site = WebSite.from_manifest(payload) + except (OSError, ValueError) as error: + parser.exit(1, f"coulobre-web-node: {error}\n") + + sys.stdout.write(site.render(args.configuration)) + return 0 From 5384d70d03198c8e30c6efdad1e8b7b0e3ae55ea Mon Sep 17 00:00:00 2001 From: Peter van Arkel Date: Thu, 19 Nov 2026 21:52:43 +0100 Subject: [PATCH 2/3] Apply web deployment manifests on Ubuntu nodes Create isolated site accounts, validate both service configurations, and roll back newly installed files when activation fails. --- docs/development.md | 33 +++ src/coulobre/hosting/test_web_node_apply.py | 75 ++++++ src/coulobre/web_node.py | 10 +- src/coulobre/web_node_apply.py | 255 ++++++++++++++++++++ 4 files changed, 372 insertions(+), 1 deletion(-) create mode 100644 src/coulobre/hosting/test_web_node_apply.py create mode 100644 src/coulobre/web_node_apply.py diff --git a/docs/development.md b/docs/development.md index 38615bb..c4f7eb5 100644 --- a/docs/development.md +++ b/docs/development.md @@ -67,6 +67,39 @@ coulobre-web-node render coulobre-web-plan-1.json php-fpm > php-fpm.conf The command reads the manifest and packaged templates locally. The isolated Ubuntu check below demonstrates loading the configuration. +## Apply a manifest on an Ubuntu web node + +Use a dedicated Ubuntu 26.04 node with Apache and PHP 8.5 FPM installed from +the distribution packages. Enable FastCGI in Apache and start the native +services before applying a manifest. + +```sh +sudo apt install apache2 php8.5-fpm +sudo a2enmod proxy_fcgi +sudo service php8.5-fpm start +sudo service apache2 restart +``` + +Install the matching Coulobre package in a root-owned virtual environment on +the node. Review the completed preview and transfer its deployment manifest +to the node. Apply it with the node operator account. + +```sh +sudo /opt/coulobre/bin/coulobre-web-node apply coulobre-web-plan-1.json +``` + +The command reserves the account ID and domain on the node, creates a system +user and a document root under `/srv/coulobre/web//public`, and +installs Apache and PHP-FPM configuration. It validates both configurations, +reloads PHP-FPM, waits for the per-site socket, then reloads Apache. + +Reapply the same manifest to retry or verify an existing installation. The +node checks the account registry for domain conflicts and protects existing +configuration files. If a configuration check or reload fails, the command +removes the configuration it added. It reloads the prior configuration for +affected services and reports any recovery errors. The account reservation and +document root stay available for the next attempt. + ## Run an isolated PHP test site Open a completed preview for the account's current domain and select **Download diff --git a/src/coulobre/hosting/test_web_node_apply.py b/src/coulobre/hosting/test_web_node_apply.py new file mode 100644 index 0000000..87989b3 --- /dev/null +++ b/src/coulobre/hosting/test_web_node_apply.py @@ -0,0 +1,75 @@ +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 install_configurations + + +class WebNodeConfigurationTests(SimpleTestCase): + def setUp(self): + directory = Path(self.enterContext(TemporaryDirectory())) + apache_available = directory / "sites-available" + apache_enabled = directory / "sites-enabled" + apache_available.mkdir() + apache_enabled.mkdir() + self.site = WebSite(42, "example.org") + self.apache = apache_available / "coulobre-42.conf" + self.enabled = apache_enabled / self.apache.name + self.pool = directory / "php.conf" + self.socket = directory / "coulobre-42.sock" + self.runner = self.enterContext(patch("coulobre.web_node_apply.run")) + self.readiness = self.enterContext( + patch("coulobre.web_node_apply.wait_for_socket") + ) + + def install(self): + install_configurations( + self.site, self.apache, self.enabled, self.pool, self.socket + ) + + def test_install_validates_both_services_before_reloading(self): + self.install() + + self.assertEqual(self.apache.read_text(), self.site.render("apache")) + self.assertEqual(self.pool.read_text(), self.site.render("php-fpm")) + self.assertEqual(self.enabled.resolve(), self.apache) + self.assertEqual( + self.runner.call_args_list, + [ + call("/usr/sbin/php-fpm8.5", "--test"), + call("/usr/sbin/apache2ctl", "configtest"), + call("/usr/sbin/service", "php8.5-fpm", "reload"), + call("/usr/sbin/service", "apache2", "reload"), + ], + ) + self.readiness.assert_called_once_with(self.socket) + + def test_failed_apache_reload_rolls_back_files_and_reloads_previous_config(self): + def fail_first_apache_reload(*command): + if ( + command == ("/usr/sbin/service", "apache2", "reload") + and self.apache.exists() + ): + raise ValueError("Apache reload failed") + + self.runner.side_effect = fail_first_apache_reload + with self.assertRaisesRegex(ValueError, "Apache reload failed"): + self.install() + + self.assertFalse(self.apache.exists()) + self.assertFalse(self.pool.exists()) + self.assertFalse(self.enabled.is_symlink()) + self.assertEqual( + self.runner.call_args_list[-2:], + [ + call("/usr/sbin/service", "php8.5-fpm", "reload"), + call("/usr/sbin/service", "apache2", "reload"), + ], + ) + + self.runner.side_effect = None + self.install() + self.assertTrue(self.enabled.is_symlink()) diff --git a/src/coulobre/web_node.py b/src/coulobre/web_node.py index 40951a9..723c922 100644 --- a/src/coulobre/web_node.py +++ b/src/coulobre/web_node.py @@ -73,13 +73,21 @@ def main(argv=None): ) render.add_argument("manifest", type=Path) render.add_argument("configuration", choices=CONFIGURATIONS) + apply = commands.add_parser("apply", help="Install a site on an Ubuntu web node.") + apply.add_argument("manifest", type=Path) args = parser.parse_args(argv) try: payload = json.loads(args.manifest.read_text(encoding="utf-8")) site = WebSite.from_manifest(payload) + if args.command == "apply": + from .web_node_apply import apply_site + + apply_site(site) + print(f"Applied web configuration for {site.domain}.") + else: + sys.stdout.write(site.render(args.configuration)) except (OSError, ValueError) as error: parser.exit(1, f"coulobre-web-node: {error}\n") - sys.stdout.write(site.render(args.configuration)) return 0 diff --git a/src/coulobre/web_node_apply.py b/src/coulobre/web_node_apply.py new file mode 100644 index 0000000..399f35d --- /dev/null +++ b/src/coulobre/web_node_apply.py @@ -0,0 +1,255 @@ +import fcntl +import grp +import json +import os +import pwd +import stat +import subprocess +import time +from pathlib import Path +from tempfile import NamedTemporaryFile + +STATE_DIRECTORY = Path("/var/lib/coulobre/web-node") +WEB_ROOT = Path("/srv/coulobre/web") +APACHE_AVAILABLE = Path("/etc/apache2/sites-available") +APACHE_ENABLED = Path("/etc/apache2/sites-enabled") +PHP_POOL_DIRECTORY = Path("/etc/php/8.5/fpm/pool.d") +PHP_SERVICE = "php8.5-fpm" + + +def apply_site(site): + if os.geteuid() != 0: + raise ValueError("Run apply as root on the web node.") + + for directory in (APACHE_AVAILABLE, APACHE_ENABLED, PHP_POOL_DIRECTORY): + require_root_directory(directory) + require_root_directory(STATE_DIRECTORY.parent, create_mode=0o750) + require_root_directory(STATE_DIRECTORY, create_mode=0o700) + require_root_directory(WEB_ROOT.parent, create_mode=0o755) + require_root_directory(WEB_ROOT, create_mode=0o755) + + with (STATE_DIRECTORY / "apply.lock").open("a") as lock: + fcntl.flock(lock, fcntl.LOCK_EX) + install_site(site) + + +def require_root_directory(path, *, create_mode=None): + for parent in reversed(path.parents): + check_root_directory(parent) + if create_mode is not None: + path.mkdir(mode=create_mode, exist_ok=True) + check_root_directory(path) + + +def check_root_directory(path): + info = path.lstat() + if not stat.S_ISDIR(info.st_mode) or info.st_uid != 0 or info.st_mode & 0o022: + raise ValueError(f"Expected a root-controlled directory at {path}.") + + +def install_site(site): + account_id = site.account_id + configuration = site.configuration() + user = configuration["service_user"] + account_dir = WEB_ROOT / str(account_id) + apache_config = APACHE_AVAILABLE / f"{user}.conf" + apache_link = APACHE_ENABLED / apache_config.name + php_config = PHP_POOL_DIRECTORY / apache_config.name + socket = Path(configuration["socket_path"]) + owned_paths = (account_dir, apache_config, apache_link, php_config, socket) + + for service in (PHP_SERVICE, "apache2"): + run("/usr/sbin/service", service, "status") + if "proxy_fcgi_module" not in run("/usr/sbin/apache2ctl", "-M"): + raise ValueError("Enable Apache's proxy_fcgi module before applying a site.") + + reserve_account(site, user, owned_paths) + uid, web_gid = ensure_system_account(user, account_dir) + require_root_directory(account_dir, create_mode=0o755) + ensure_public_directory(account_dir / "public", uid, web_gid) + install_configurations(site, apache_config, apache_link, php_config, socket) + + +def reserve_account(site, user, paths): + marker = STATE_DIRECTORY / f"{site.account_id}.json" + manifest = site.manifest() + for existing in STATE_DIRECTORY.glob("*.json"): + saved = json.loads(read_root_file(existing)) + if existing == marker: + if saved != manifest: + raise ValueError( + "The account is already reserved with a different manifest." + ) + elif saved["domain"] == site.domain: + raise ValueError( + "The primary domain is already reserved by another account." + ) + + if os.path.lexists(marker): + return + if ( + current_user(user) + or current_group(user) + or any(os.path.lexists(p) for p in paths) + ): + raise ValueError( + "The web node already has unmanaged resources for this account." + ) + write_new_file(marker, json.dumps(manifest) + "\n", mode=0o600) + + +def current_user(name): + try: + return pwd.getpwnam(name) + except KeyError: + return None + + +def current_group(name): + try: + return grp.getgrnam(name) + except KeyError: + return None + + +def ensure_system_account(user, account_dir): + account = current_user(user) + group = current_group(user) + shell = "/usr/sbin/nologin" + if account is None: + group_options = ("--user-group",) + if group is not None: + if group.gr_mem or not group.gr_gid: + raise ValueError(f"Unexpected members or ID in the {user} group.") + group_options = ("--gid", str(group.gr_gid)) + run( + "/usr/sbin/useradd", + "--system", + *group_options, + "--no-create-home", + "--home-dir", + str(account_dir), + "--shell", + shell, + user, + ) + account = pwd.getpwnam(user) + group = grp.getgrnam(user) + + if ( + not account.pw_uid + or group is None + or not group.gr_gid + or group.gr_mem + or account.pw_gid != group.gr_gid + or account.pw_dir != str(account_dir) + or account.pw_shell != shell + ): + raise ValueError(f"Unexpected user or group configuration for {user}.") + + return account.pw_uid, grp.getgrnam("www-data").gr_gid + + +def ensure_public_directory(path, uid, gid): + if not os.path.lexists(path): + path.mkdir(mode=0o700) + info = path.lstat() + if stat.S_ISDIR(info.st_mode) and info.st_uid == 0 and not any(path.iterdir()): + path.chmod(0o750) + os.chown(path, uid, gid, follow_symlinks=False) + info = path.lstat() + if ( + not stat.S_ISDIR(info.st_mode) + or (info.st_uid, info.st_gid) != (uid, gid) + or stat.S_IMODE(info.st_mode) != 0o750 + ): + raise ValueError(f"Unexpected ownership or mode for {path}.") + + +def read_root_file(path): + info = path.lstat() + if not stat.S_ISREG(info.st_mode) or info.st_uid != 0 or info.st_mode & 0o022: + raise ValueError(f"Expected a root-controlled file at {path}.") + return path.read_text(encoding="utf-8") + + +def write_new_file(path, content, *, mode): + with NamedTemporaryFile(mode="w", encoding="utf-8", dir=path.parent) as staged: + staged.write(content) + staged.flush() + os.fchmod(staged.fileno(), mode) + os.link(staged.name, path) + + +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): + if read_root_file(path) != content: + raise ValueError(f"Existing configuration differs at {path}.") + else: + write_new_file(path, content, mode=0o644) + created.append(path) + + link_target = Path("../sites-available") / apache.name + if os.path.lexists(enabled): + if not enabled.is_symlink() or enabled.readlink() != link_target: + raise ValueError(f"Existing Apache site link differs at {enabled}.") + else: + enabled.symlink_to(link_target) + created.append(enabled) + + run("/usr/sbin/php-fpm8.5", "--test") + run("/usr/sbin/apache2ctl", "configtest") + reload_attempts.append(PHP_SERVICE) + run("/usr/sbin/service", PHP_SERVICE, "reload") + wait_for_socket(socket) + reload_attempts.append("apache2") + run("/usr/sbin/service", "apache2", "reload") + except (OSError, ValueError, KeyboardInterrupt) as error: + failures = [] + for path in reversed(created): + try: + path.unlink(missing_ok=True) + except OSError as rollback_error: + failures.append(str(rollback_error)) + for service in reload_attempts: + try: + run("/usr/sbin/service", service, "reload") + except (OSError, ValueError) as rollback_error: + failures.append(str(rollback_error)) + if failures: + raise ValueError( + f"{error}\nRollback errors:\n" + "\n".join(failures) + ) from error + raise + + +def wait_for_socket(path): + deadline = time.monotonic() + 15 + while time.monotonic() < deadline: + try: + if stat.S_ISSOCK(path.lstat().st_mode): + return + except FileNotFoundError: + pass + time.sleep(0.1) + raise ValueError(f"PHP-FPM did not open {path}.") + + +def run(*command): + process = subprocess.run( + command, + capture_output=True, + text=True, + env={"PATH": "/usr/sbin:/usr/bin:/sbin:/bin", "LANG": "C"}, + ) + if process.returncode: + message = process.stderr.strip() or process.stdout.strip() + raise ValueError( + f"{' '.join(command)} failed ({process.returncode}). {message}" + ) + return process.stdout From af16adf2167696ed52aa21ba65f1ef385cd60272 Mon Sep 17 00:00:00 2001 From: Peter van Arkel Date: Thu, 19 Nov 2026 22:02:06 +0100 Subject: [PATCH 3/3] Add local web deployment status checks --- docs/development.md | 17 +++ src/coulobre/hosting/test_web_node_apply.py | 51 ++++++- src/coulobre/web_node.py | 10 ++ src/coulobre/web_node_apply.py | 158 +++++++++++++++----- 4 files changed, 199 insertions(+), 37 deletions(-) diff --git a/docs/development.md b/docs/development.md index c4f7eb5..bbaab14 100644 --- a/docs/development.md +++ b/docs/development.md @@ -100,6 +100,23 @@ removes the configuration it added. It reloads the prior configuration for affected services and reports any recovery errors. The account reservation and document root stay available for the next attempt. +Check the local deployment state with the same manifest. + +```sh +sudo /opt/coulobre/bin/coulobre-web-node status coulobre-web-plan-1.json +``` + +The JSON report includes the manifest identity and one of three states. + +- `configured` means the reservation, Unix account, document root, service + configuration, running services, and PHP-FPM socket match the manifest. +- `not_installed` means the node has no reservation for the account. +- `needs_attention` includes the first mismatch or service problem found. + +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. + ## Run an isolated PHP test site Open a completed preview for the account's current domain and select **Download diff --git a/src/coulobre/hosting/test_web_node_apply.py b/src/coulobre/hosting/test_web_node_apply.py index 87989b3..342d009 100644 --- a/src/coulobre/hosting/test_web_node_apply.py +++ b/src/coulobre/hosting/test_web_node_apply.py @@ -1,3 +1,4 @@ +import json from pathlib import Path from tempfile import TemporaryDirectory from unittest.mock import call, patch @@ -5,7 +6,7 @@ from unittest.mock import call, patch from django.test import SimpleTestCase from coulobre.web_node import WebSite -from coulobre.web_node_apply import install_configurations +from coulobre.web_node_apply import install_configurations, site_status class WebNodeConfigurationTests(SimpleTestCase): @@ -73,3 +74,51 @@ class WebNodeConfigurationTests(SimpleTestCase): self.runner.side_effect = None self.install() self.assertTrue(self.enabled.is_symlink()) + + +class WebNodeStatusTests(SimpleTestCase): + def setUp(self): + self.state = Path(self.enterContext(TemporaryDirectory())) + self.site = WebSite(42, "example.org") + self.marker = self.state / "42.json" + self.enterContext(patch("coulobre.web_node_apply.STATE_DIRECTORY", self.state)) + self.enterContext(patch("coulobre.web_node_apply.os.geteuid", return_value=0)) + self.enterContext(patch("coulobre.web_node_apply.require_root_directory")) + self.enterContext( + patch("coulobre.web_node_apply.read_root_file", side_effect=Path.read_text) + ) + self.inspect = self.enterContext( + patch("coulobre.web_node_apply.check_installation") + ) + + def reserve(self, site): + self.marker.write_text(json.dumps(site.manifest()), encoding="utf-8") + (self.state / "apply.lock").touch() + + def test_unreserved_account_leaves_state_untouched(self): + self.assertEqual(site_status(self.site)["state"], "not_installed") + self.assertEqual(list(self.state.iterdir()), []) + self.inspect.assert_not_called() + + def test_configured_account_then_reports_local_drift(self): + self.reserve(self.site) + self.assertEqual(site_status(self.site)["state"], "configured") + + self.inspect.side_effect = ValueError("The configuration has changed.") + self.assertEqual( + site_status(self.site), + { + **self.site.manifest(), + "state": "needs_attention", + "problem": "The configuration has changed.", + }, + ) + + def test_different_manifest_reports_a_conflict_without_inspecting_files(self): + self.reserve(WebSite(42, "different.example")) + + report = site_status(self.site) + + self.assertEqual(report["state"], "needs_attention") + self.assertIn("different manifest", report["problem"]) + self.inspect.assert_not_called() diff --git a/src/coulobre/web_node.py b/src/coulobre/web_node.py index 723c922..40a9146 100644 --- a/src/coulobre/web_node.py +++ b/src/coulobre/web_node.py @@ -75,6 +75,10 @@ def main(argv=None): render.add_argument("configuration", choices=CONFIGURATIONS) apply = commands.add_parser("apply", help="Install a site on an Ubuntu web node.") apply.add_argument("manifest", type=Path) + status = commands.add_parser( + "status", help="Check a site's local configuration and services." + ) + status.add_argument("manifest", type=Path) args = parser.parse_args(argv) try: @@ -85,6 +89,12 @@ def main(argv=None): apply_site(site) print(f"Applied web configuration for {site.domain}.") + elif args.command == "status": + from .web_node_apply import site_status + + report = site_status(site) + print(json.dumps(report, indent=2)) + return 0 if report["state"] == "configured" else 2 else: sys.stdout.write(site.render(args.configuration)) except (OSError, ValueError) as error: diff --git a/src/coulobre/web_node_apply.py b/src/coulobre/web_node_apply.py index 399f35d..24ccc7e 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 dataclasses import dataclass from pathlib import Path from tempfile import NamedTemporaryFile @@ -15,6 +16,28 @@ APACHE_AVAILABLE = Path("/etc/apache2/sites-available") APACHE_ENABLED = Path("/etc/apache2/sites-enabled") PHP_POOL_DIRECTORY = Path("/etc/php/8.5/fpm/pool.d") PHP_SERVICE = "php8.5-fpm" +SITE_SHELL = "/usr/sbin/nologin" + + +@dataclass(frozen=True) +class SitePaths: + account: Path + apache: Path + enabled: Path + pool: Path + socket: Path + + @classmethod + def for_site(cls, site): + configuration = site.configuration() + name = f"{configuration['service_user']}.conf" + return cls( + account=WEB_ROOT / str(site.account_id), + apache=APACHE_AVAILABLE / name, + enabled=APACHE_ENABLED / name, + pool=PHP_POOL_DIRECTORY / name, + socket=Path(configuration["socket_path"]), + ) def apply_site(site): @@ -48,26 +71,66 @@ def check_root_directory(path): def install_site(site): - account_id = site.account_id - configuration = site.configuration() - user = configuration["service_user"] - account_dir = WEB_ROOT / str(account_id) - apache_config = APACHE_AVAILABLE / f"{user}.conf" - apache_link = APACHE_ENABLED / apache_config.name - php_config = PHP_POOL_DIRECTORY / apache_config.name - socket = Path(configuration["socket_path"]) - owned_paths = (account_dir, apache_config, apache_link, php_config, socket) + user = site.configuration()["service_user"] + paths = SitePaths.for_site(site) + owned_paths = (paths.account, paths.apache, paths.enabled, paths.pool, paths.socket) + check_services() + reserve_account(site, user, owned_paths) + uid, web_gid = ensure_system_account(user, paths.account) + require_root_directory(paths.account, create_mode=0o755) + ensure_public_directory(paths.account / "public", uid, web_gid) + install_configurations(site, paths.apache, paths.enabled, paths.pool, paths.socket) + +def site_status(site): + if os.geteuid() != 0: + raise ValueError("Run status as root on the web node.") + + report = {**site.manifest(), "state": "not_installed", "problem": None} + try: + require_root_directory(STATE_DIRECTORY) + except FileNotFoundError: + return report + marker = STATE_DIRECTORY / f"{site.account_id}.json" + if not os.path.lexists(marker): + return report + + with (STATE_DIRECTORY / "apply.lock").open("r") as lock: + fcntl.flock(lock, fcntl.LOCK_SH) + try: + if json.loads(read_root_file(marker)) != site.manifest(): + raise ValueError("The account is reserved with a different manifest.") + check_installation(site, SitePaths.for_site(site)) + except (OSError, ValueError) as error: + return {**report, "state": "needs_attention", "problem": str(error)} + return {**report, "state": "configured"} + + +def check_installation(site, paths): + for directory in ( + paths.account, + APACHE_AVAILABLE, + APACHE_ENABLED, + PHP_POOL_DIRECTORY, + ): + require_root_directory(directory) + + user = site.configuration()["service_user"] + uid, gid = check_system_account(user, paths.account) + check_public_directory(paths.account / "public", uid, gid) + check_configuration(paths.apache, site.render("apache")) + check_configuration(paths.pool, site.render("php-fpm")) + check_site_link(paths.enabled, Path("../sites-available") / paths.apache.name) + check_services() + if not socket_exists(paths.socket): + raise ValueError(f"PHP-FPM is missing the site socket at {paths.socket}.") + + +def check_services(): for service in (PHP_SERVICE, "apache2"): run("/usr/sbin/service", service, "status") if "proxy_fcgi_module" not in run("/usr/sbin/apache2ctl", "-M"): - raise ValueError("Enable Apache's proxy_fcgi module before applying a site.") - - reserve_account(site, user, owned_paths) - uid, web_gid = ensure_system_account(user, account_dir) - require_root_directory(account_dir, create_mode=0o755) - ensure_public_directory(account_dir / "public", uid, web_gid) - install_configurations(site, apache_config, apache_link, php_config, socket) + raise ValueError("Enable Apache's proxy_fcgi module on the web node.") def reserve_account(site, user, paths): @@ -113,11 +176,9 @@ def current_group(name): def ensure_system_account(user, account_dir): - account = current_user(user) - group = current_group(user) - shell = "/usr/sbin/nologin" - if account is None: + if current_user(user) is None: group_options = ("--user-group",) + group = current_group(user) if group is not None: if group.gr_mem or not group.gr_gid: raise ValueError(f"Unexpected members or ID in the {user} group.") @@ -130,24 +191,31 @@ def ensure_system_account(user, account_dir): "--home-dir", str(account_dir), "--shell", - shell, + SITE_SHELL, user, ) - account = pwd.getpwnam(user) - group = grp.getgrnam(user) + return check_system_account(user, account_dir) + +def check_system_account(user, account_dir): + account = current_user(user) + group = current_group(user) if ( - not account.pw_uid + account is None + or not account.pw_uid or group is None or not group.gr_gid or group.gr_mem or account.pw_gid != group.gr_gid or account.pw_dir != str(account_dir) - or account.pw_shell != shell + or account.pw_shell != SITE_SHELL ): raise ValueError(f"Unexpected user or group configuration for {user}.") - return account.pw_uid, grp.getgrnam("www-data").gr_gid + web_group = current_group("www-data") + if web_group is None: + raise ValueError("The Apache www-data group is missing.") + return account.pw_uid, web_group.gr_gid def ensure_public_directory(path, uid, gid): @@ -157,7 +225,11 @@ def ensure_public_directory(path, uid, gid): if stat.S_ISDIR(info.st_mode) and info.st_uid == 0 and not any(path.iterdir()): path.chmod(0o750) os.chown(path, uid, gid, follow_symlinks=False) - info = path.lstat() + check_public_directory(path, uid, gid) + + +def check_public_directory(path, uid, gid): + info = path.lstat() if ( not stat.S_ISDIR(info.st_mode) or (info.st_uid, info.st_gid) != (uid, gid) @@ -188,16 +260,14 @@ def install_configurations(site, apache, enabled, pool, socket): for path, name in ((apache, "apache"), (pool, "php-fpm")): content = site.render(name) if os.path.lexists(path): - if read_root_file(path) != content: - raise ValueError(f"Existing configuration differs at {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): - if not enabled.is_symlink() or enabled.readlink() != link_target: - raise ValueError(f"Existing Apache site link differs at {enabled}.") + check_site_link(enabled, link_target) else: enabled.symlink_to(link_target) created.append(enabled) @@ -228,18 +298,34 @@ def install_configurations(site, apache, enabled, pool, socket): raise +def check_configuration(path, content): + if read_root_file(path) != content: + raise ValueError(f"Existing configuration differs at {path}.") + + +def check_site_link(enabled, target): + if not enabled.is_symlink() or enabled.readlink() != target: + raise ValueError( + f"Expected the Apache site link at {enabled} to point to {target}." + ) + + def wait_for_socket(path): deadline = time.monotonic() + 15 while time.monotonic() < deadline: - try: - if stat.S_ISSOCK(path.lstat().st_mode): - return - except FileNotFoundError: - pass + if socket_exists(path): + return time.sleep(0.1) raise ValueError(f"PHP-FPM did not open {path}.") +def socket_exists(path): + try: + return stat.S_ISSOCK(path.lstat().st_mode) + except FileNotFoundError: + return False + + def run(*command): process = subprocess.run( command,