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.
This commit is contained in:
parkel committed 2026-11-19 21:44:15 +01:00
1 parent a12d428023
commit aea049087d
15 files changed
+239 -44

No files matched your search

+16
View File
@@ -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
+3 -9
View File
@@ -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
+3 -5
View File
@@ -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())
@@ -1,14 +1,14 @@
<VirtualHost *:80>
ServerName {{ domain }}
DocumentRoot "{{ document_root }}"
ServerName $domain
DocumentRoot "$document_root"
<Directory "{{ document_root }}">
<Directory "$document_root">
AllowOverride None
Options None
Require all granted
</Directory>
<FilesMatch "\.php$">
SetHandler "proxy:unix:{{ socket_path }}|fcgi://localhost/"
<FilesMatch "\.php$$">
SetHandler "proxy:unix:$socket_path|fcgi://localhost/"
</FilesMatch>
</VirtualHost>
@@ -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
@@ -24,7 +24,10 @@
<header class="section-heading">
<h2 id="configuration-heading">Virtual host configuration</h2>
{% if plan.can_export %}
<a class="button secondary" href="{% url 'panel:download_smoke_bundle' plan.pk %}">Download test bundle</a>
<div class="form-actions">
<a class="button secondary" href="{% url 'panel:download_deployment_manifest' plan.pk %}">Download deployment manifest</a>
<a class="button secondary" href="{% url 'panel:download_smoke_bundle' plan.pk %}">Download test bundle</a>
</div>
{% endif %}
</header>
<pre class="configuration"><code>{{ plan.apache_config }}</code></pre>
+32
View File
@@ -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(),
)
@@ -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)
+6 -1
View File
@@ -26,7 +26,12 @@ urlpatterns = [
path("plans/<int:pk>/", views.PlanDetail.as_view(), name="plan"),
path(
"plans/<int:pk>/smoke-bundle/",
views.DownloadWebSmokeBundle.as_view(),
views.DownloadWebPlan.as_view(),
name="download_smoke_bundle",
),
path(
"plans/<int:pk>/deployment-manifest/",
views.DownloadWebPlan.as_view(manifest=True),
name="download_deployment_manifest",
),
]
+17 -5
View File
@@ -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}"'
),
},
)
+8 -12
View File
@@ -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"),
}
+85
View File
@@ -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