Compare commits

...
4 Commits
Author SHA1 Message Date
parkel 0b12ea5a44 Document website alias DNS and HTTPS setup
Coulobre Panel CI / Checks (Python 3.12) (pull_request) Canceled after 0s
Coulobre Panel CI / Checks (Python 3.14) (pull_request) Canceled after 0s
2026-11-21 15:32:02 +01:00
parkel 727f7b2c28 Manage website aliases and their HTTPS status in the panel 2026-11-21 15:32:02 +01:00
parkel 077332c1bb Reserve website hostnames and dispatch alias lifecycle jobs 2026-11-21 15:32:02 +01:00
parkel e4f31cec2f Serve website aliases through Apache and Certbot 2026-11-21 15:32:02 +01:00
18 changed files with 1389 additions and 37 deletions

No files matched your search

+28
View File
@@ -221,6 +221,34 @@ the managed sites. Use **Change storage limit** on the deployed account to
apply the hosting plan's default or choose a per-site value. apply the hosting plan's default or choose a per-site value.
[Website storage quotas](development.md#apply-a-website-storage-limit) [Website storage quotas](development.md#apply-a-website-storage-limit)
### Serve additional hostnames on a website
After activating a website, use **Add alias** on the hosting account.
The alias uses the same document root and PHP-FPM pool as the primary domain.
Operators need **Can manage website aliases** and permission to view hosting
accounts. Apache hostname matching selects the virtual host for the alias.
[Apache name-based virtual hosts](https://httpd.apache.org/docs/current/en/vhosts/name-based.html)
Point the alias to the same address or reverse proxy as the primary
domain. Add the DNS records where that hostname is managed. A reverse proxy
must forward the alias in the original Host header. Only use hostnames that
you control. The panel reserves each hostname for one website and checks
existing Apache hostnames when activating an alias.
Once the alias is active, select **Enable HTTPS** with the permissions and
local HTTPS worker described below. The alias uses its own Certbot lineage.
HTTP-01 must reach the web node for the alias hostname. Certbot renews it
using the same renewal hook as the primary website.
Selecting **Remove** disables the alias virtual hosts and deletes the
dedicated Certbot lineage. Check the result in the account before reusing
the hostname. Remove aliases before deleting an account or editing its
primary domain. An unmatched hostname can still reach Apache's default virtual
host while its DNS points at the node. Use a default virtual host that
serves no tenant content when unknown hosts should be rejected.
[Apache default virtual host](https://httpd.apache.org/docs/current/en/vhosts/name-based.html#defaultvhost) ·
[Deleting a Certbot certificate](https://eff-certbot.readthedocs.io/en/stable/using.html#deleting-certificates)
## Enable HTTPS for hosted websites ## Enable HTTPS for hosted websites
Once a site is active, obtain the website certificate with Certbot on the Once a site is active, obtain the website certificate with Certbot on the
+9 -1
View File
@@ -810,7 +810,15 @@ 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 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. or inspect the node. Use an HTTP request to verify the site's response as well.
### Enable HTTPS for a hosted website #Website aliases reuse the activation and HTTPS sockets. The web node stores
alias reservations under `/var/lib/coulobre/web-node/aliases/` and creates
separate Apache virtual hosts that share the primary site's document root and
PHP-FPM socket. Existing website deployment manifests use the primary domain
as their identity.
See [managing aliases in the panel](deployment.md#serve-additional-hostnames-on-a-website).
## Enable HTTPS for a hosted website
Apply the web deployment manifest first. Use Certbot to obtain and renew Apply the web deployment manifest first. Use Certbot to obtain and renew
the website's Let's Encrypt certificate. The HTTP-01 challenge requires the website's Let's Encrypt certificate. The HTTP-01 challenge requires
@@ -15,6 +15,7 @@ from .models import (
HostingDnsZone, HostingDnsZone,
HostingMailbox, HostingMailbox,
HostingMailDomain, HostingMailDomain,
WebsiteDomain,
) )
@@ -154,6 +155,19 @@ def domain_conflicts(domain):
conflicts.append( conflicts.append(
{"kind": kind, "domain": domain, "account_id": owner} {"kind": kind, "domain": domain, "account_id": owner}
) )
alias_owner = (
WebsiteDomain.objects.filter(domain=domain, is_primary=False)
.values_list("account_id", flat=True)
.first()
)
if alias_owner is not None:
conflicts.append(
{
"kind": "website_alias",
"domain": domain,
"account_id": alias_owner,
}
)
return conflicts return conflicts
@@ -0,0 +1,126 @@
# Generated by Django 5.2.19 on 2026-11-21 14:24
import django.db.models.deletion
import django.utils.timezone
from django.db import migrations, models
import coulobre.hosting.fields
def reserve_existing_primary_domains(apps, schema_editor):
account_model = apps.get_model("hosting", "HostingAccount")
domain_model = apps.get_model("hosting", "WebsiteDomain")
alias = schema_editor.connection.alias
accounts = account_model.objects.using(alias).values_list(
"pk", "primary_domain"
)
domain_model.objects.using(alias).bulk_create(
(
domain_model(account_id=account_id, domain=domain, is_primary=True)
for account_id, domain in accounts.iterator()
),
batch_size=500,
)
class Migration(migrations.Migration):
dependencies = [
("hosting", "0028_backup_archive_retention"),
]
operations = [
migrations.CreateModel(
name="WebsiteDomain",
fields=[
(
"id",
models.BigAutoField(
auto_created=True,
primary_key=True,
serialize=False,
verbose_name="ID",
),
),
(
"domain",
coulobre.hosting.fields.DomainNameField(
max_length=253, unique=True
),
),
("is_primary", models.BooleanField(default=False)),
(
"account",
models.ForeignKey(
on_delete=django.db.models.deletion.CASCADE,
related_name="website_domains",
to="hosting.hostingaccount",
),
),
],
),
migrations.CreateModel(
name="WebsiteAlias",
fields=[
(
"id",
models.BigAutoField(
auto_created=True,
primary_key=True,
serialize=False,
verbose_name="ID",
),
),
(
"requested_at",
models.DateTimeField(default=django.utils.timezone.now),
),
(
"last_dispatched_at",
models.DateTimeField(blank=True, null=True),
),
("started_at", models.DateTimeField(blank=True, null=True)),
("finished_at", models.DateTimeField(blank=True, null=True)),
("problem", models.TextField(blank=True)),
(
"primary_domain",
coulobre.hosting.fields.DomainNameField(max_length=253),
),
(
"operation",
models.CharField(
choices=[
("activate", "Activate alias"),
("https", "Enable HTTPS"),
("remove", "Remove alias"),
],
default="activate",
max_length=8,
),
),
("http_active", models.BooleanField(default=False)),
("https_active", models.BooleanField(default=False)),
(
"reservation",
models.OneToOneField(
on_delete=django.db.models.deletion.PROTECT,
related_name="alias",
to="hosting.websitedomain",
),
),
],
options={
"permissions": [
("manage_website_aliases", "Can manage website aliases")
],
"indexes": [
models.Index(
fields=["operation", "finished_at", "requested_at"],
name="hosting_web_operati_d0d207_idx",
)
],
},
),
migrations.RunPython(
reserve_existing_primary_domains, migrations.RunPython.noop
),
]
+100 -1
View File
@@ -1,12 +1,13 @@
import uuid import uuid
from django.conf import settings from django.conf import settings
from django.core.exceptions import ValidationError
from django.core.validators import ( from django.core.validators import (
MaxValueValidator, MaxValueValidator,
MinValueValidator, MinValueValidator,
RegexValidator, RegexValidator,
) )
from django.db import models from django.db import models, router, transaction
from django.urls import reverse from django.urls import reverse
from django.utils import timezone from django.utils import timezone
@@ -206,9 +207,82 @@ class HostingAccount(models.Model):
def __str__(self): def __str__(self):
return str(self.primary_domain) return str(self.primary_domain)
def save(self, *args, **kwargs):
update_fields = kwargs.get("update_fields")
if update_fields is not None and "primary_domain" not in update_fields:
return super().save(*args, **kwargs)
self.primary_domain = self._meta.get_field("primary_domain").to_python(
self.primary_domain
)
using = kwargs.get("using") or router.db_for_write(
type(self), instance=self
)
with transaction.atomic(using=using):
super().save(*args, **kwargs)
claims = WebsiteDomain.objects.using(using).filter(account=self)
primary = claims.filter(is_primary=True).first()
if primary is None:
claims.create(
domain=self.primary_domain, account=self, is_primary=True
)
elif primary.domain != self.primary_domain:
if claims.filter(is_primary=False).exists():
raise ValidationError(
{
"primary_domain": (
"Remove website aliases before changing the "
"primary domain."
),
}
)
primary.domain = self.primary_domain
primary.save(update_fields=["domain"], using=using)
def get_absolute_url(self): def get_absolute_url(self):
return reverse("panel:account", kwargs={"pk": self.pk}) return reverse("panel:account", kwargs={"pk": self.pk})
def clean(self):
super().clean()
if not self.primary_domain:
return
if WebsiteDomain.objects.filter(
domain=self.primary_domain, is_primary=False
).exists():
raise ValidationError(
{"primary_domain": "This domain is unavailable."}
)
if self.pk:
claims = self.website_domains
if (
claims.filter(is_primary=False).exists()
and claims.filter(is_primary=True)
.exclude(domain=self.primary_domain)
.exists()
):
raise ValidationError(
{
"primary_domain": (
"Remove website aliases before changing the "
"primary domain."
)
}
)
class WebsiteDomain(models.Model):
account = models.ForeignKey(
HostingAccount,
on_delete=models.CASCADE,
related_name="website_domains",
)
domain = DomainNameField(max_length=253, unique=True)
is_primary = models.BooleanField(default=False)
def __str__(self):
return self.domain
class HostingDatabase(models.Model): class HostingDatabase(models.Model):
account = models.ForeignKey( account = models.ForeignKey(
@@ -438,6 +512,31 @@ class WebHTTPS(ProvisioningJob):
verbose_name = "website HTTPS request" verbose_name = "website HTTPS request"
class WebsiteAlias(ProvisioningJob):
class Operation(models.TextChoices):
ACTIVATE = "activate", "Activate alias"
HTTPS = "https", "Enable HTTPS"
REMOVE = "remove", "Remove alias"
reservation = models.OneToOneField(
WebsiteDomain, on_delete=models.PROTECT, related_name="alias"
)
primary_domain = DomainNameField(max_length=253)
operation = models.CharField(
max_length=8, choices=Operation, default=Operation.ACTIVATE
)
http_active = models.BooleanField(default=False)
https_active = models.BooleanField(default=False)
class Meta:
indexes = [
models.Index(fields=("operation", "finished_at", "requested_at"))
]
permissions = [
("manage_website_aliases", "Can manage website aliases")
]
class SiteSFTP(ProvisioningJob): class SiteSFTP(ProvisioningJob):
account = models.OneToOneField( account = models.OneToOneField(
HostingAccount, on_delete=models.CASCADE, related_name="sftp" HostingAccount, on_delete=models.CASCADE, related_name="sftp"
+10
View File
@@ -12,6 +12,7 @@ from coulobre.account_restore_request import (
from coulobre.mail_node import MailboxQuotaUpdate from coulobre.mail_node import MailboxQuotaUpdate
from coulobre.web_node import ( from coulobre.web_node import (
MAX_STORAGE_BYTES, MAX_STORAGE_BYTES,
WebAliasRequest,
WebQuotaRequest, WebQuotaRequest,
WebStorageRequest, WebStorageRequest,
) )
@@ -55,6 +56,15 @@ def enable_local_https(site):
) )
def update_local_website_alias(alias, operation):
apply_on_local_node(
WebAliasRequest(alias, operation),
"/run/coulobre-web-apply.sock",
"web node",
"website alias",
)
def update_local_sftp(keys): def update_local_sftp(keys):
apply_on_local_node( apply_on_local_node(
keys, keys,
+82 -1
View File
@@ -3,6 +3,7 @@ from uuid import UUID
from celery import shared_task from celery import shared_task
from django.conf import settings from django.conf import settings
from django.db import transaction
from django.db.models import Q from django.db.models import Q
from django.utils import timezone from django.utils import timezone
@@ -19,7 +20,7 @@ from coulobre.account_restore_request import (
) )
from coulobre.dns_node import DnsZone from coulobre.dns_node import DnsZone
from coulobre.sftp_keys import SFTPKeys from coulobre.sftp_keys import SFTPKeys
from coulobre.web_node import WebSite from coulobre.web_node import WebAlias, WebSite
from .account_backups import queue_due_account_backups from .account_backups import queue_due_account_backups
from .backup_restores import ( from .backup_restores import (
@@ -41,6 +42,7 @@ from .models import (
WebActivation, WebActivation,
WebHTTPS, WebHTTPS,
WebProvisioningPlan, WebProvisioningPlan,
WebsiteAlias,
WebsiteRestoreJob, WebsiteRestoreJob,
) )
from .node_client import ( from .node_client import (
@@ -57,6 +59,7 @@ from .node_client import (
set_local_site_storage_limit, set_local_site_storage_limit,
update_local_mailbox_quota, update_local_mailbox_quota,
update_local_sftp, update_local_sftp,
update_local_website_alias,
) )
from .sftp import site_is_active from .sftp import site_is_active
@@ -117,6 +120,15 @@ def dispatch_web_activations():
dispatch_provisioning_jobs( dispatch_provisioning_jobs(
WebActivation, activate_web_plan, WEB_ACTIVATION_QUEUE WebActivation, activate_web_plan, WEB_ACTIVATION_QUEUE
) )
dispatch_provisioning_jobs(
WebsiteAlias,
update_website_alias,
WEB_ACTIVATION_QUEUE,
operation__in=(
WebsiteAlias.Operation.ACTIVATE,
WebsiteAlias.Operation.REMOVE,
),
)
@shared_task @shared_task
@@ -139,6 +151,13 @@ def dispatch_site_storage_limits():
def dispatch_web_https(): def dispatch_web_https():
if settings.LOCAL_WEB_HTTPS: if settings.LOCAL_WEB_HTTPS:
dispatch_provisioning_jobs(WebHTTPS, enable_web_https, WEB_HTTPS_QUEUE) dispatch_provisioning_jobs(WebHTTPS, enable_web_https, WEB_HTTPS_QUEUE)
if settings.LOCAL_WEB_ACTIVATION:
dispatch_provisioning_jobs(
WebsiteAlias,
enable_website_alias_https,
WEB_HTTPS_QUEUE,
operation=WebsiteAlias.Operation.HTTPS,
)
@shared_task @shared_task
@@ -261,6 +280,68 @@ def apply_web_activation(activation):
activate_local_site(WebSite(plan.account_id, plan.primary_domain)) activate_local_site(WebSite(plan.account_id, plan.primary_domain))
@shared_task(acks_late=True, reject_on_worker_lost=True)
def update_website_alias(alias_id):
if settings.LOCAL_WEB_ACTIVATION:
jobs = WebsiteAlias.objects.select_related(
"reservation__account"
).exclude(operation=WebsiteAlias.Operation.HTTPS)
run_provisioning_job(
jobs,
alias_id,
apply_website_alias,
"Could not contact the local web node. "
"Check its socket and try again.",
)
def apply_website_alias(job):
alias = queued_website_alias(job)
if job.operation == WebsiteAlias.Operation.REMOVE:
update_local_website_alias(alias, "remove_alias")
with transaction.atomic():
reservation = job.reservation
job.delete()
reservation.delete()
return {}
update_local_website_alias(alias, "apply_alias")
return {"http_active": True}
@shared_task(acks_late=True, reject_on_worker_lost=True)
def enable_website_alias_https(alias_id):
if settings.LOCAL_WEB_ACTIVATION and settings.LOCAL_WEB_HTTPS:
jobs = WebsiteAlias.objects.select_related(
"reservation__account"
).filter(operation=WebsiteAlias.Operation.HTTPS)
run_provisioning_job(
jobs,
alias_id,
apply_alias_https,
"Could not contact the local HTTPS service. "
"Check its socket and try again.",
)
def apply_alias_https(job):
enable_local_https(queued_website_alias(job))
return {"https_active": True}
def queued_website_alias(job):
account = job.reservation.account
if (
job.operation != WebsiteAlias.Operation.REMOVE
and job.primary_domain != account.primary_domain
):
raise ValueError(
"The primary domain changed before the alias request ran."
)
return WebAlias(
WebSite(account.pk, job.primary_domain), job.reservation.domain
)
@shared_task(acks_late=True, reject_on_worker_lost=True) @shared_task(acks_late=True, reject_on_worker_lost=True)
def measure_site_storage(request_id): def measure_site_storage(request_id):
if settings.LOCAL_WEB_ACTIVATION: if settings.LOCAL_WEB_ACTIVATION:
@@ -40,6 +40,9 @@
{% if can_measure_site_storage or website_storage.measured_at or can_change_site_storage_limit or website_limit.applied_at %} {% if can_measure_site_storage or website_storage.measured_at or can_change_site_storage_limit or website_limit.applied_at %}
{% include "hosting/site_storage.html" %} {% include "hosting/site_storage.html" %}
{% endif %} {% endif %}
{% if website_aliases or can_add_website_alias %}
{% include "hosting/website_aliases.html" %}
{% endif %}
{% if show_account_backups %} {% if show_account_backups %}
{% include "hosting/account_backups.html" %} {% include "hosting/account_backups.html" %}
{% endif %} {% endif %}
@@ -0,0 +1,26 @@
{% extends "hosting/base.html" %}
{% block title %}{{ title }} · Coulobre Panel{% endblock %}
{% block content %}
<a class="back-link" href="{{ account.get_absolute_url }}#website-aliases-heading">← {{ account.name }}</a>
<header class="page-heading">
<div>
<h1>{{ title }}</h1>
<p class="heading-meta domain">{% if alias %}{{ alias.reservation.domain }}{% else %}{{ account.primary_domain }}{% endif %}</p>
</div>
</header>
<section class="surface editor-surface">
<form method="post" class="editor">
{% if action == "https" %}
<p>Point the hostname to this web node and make its HTTP-01 challenge reachable before requesting a certificate.</p>
{% elif action == "remove" %}
<p>This removes the alias from Apache and deletes its dedicated certificate if one exists.</p>
{% endif %}
{% csrf_token %}
{{ form.as_div }}
<div class="form-actions">
<button class="button primary" type="submit">{{ submit_label }}</button>
<a class="button secondary" href="{{ account.get_absolute_url }}#website-aliases-heading">Cancel</a>
</div>
</form>
</section>
{% endblock %}
@@ -0,0 +1,52 @@
<section class="surface" aria-labelledby="website-aliases-heading">
<header class="section-heading">
<div>
<h2 id="website-aliases-heading">Website aliases</h2>
<p class="heading-meta">Additional hostnames for this website.</p>
</div>
{% if can_add_website_alias %}
<a class="button primary" href="{% url 'panel:website_alias_create' account.pk %}">Add alias</a>
{% endif %}
</header>
{% if website_aliases %}
<div class="table-scroll">
<table>
<thead>
<tr><th scope="col">Hostname</th><th scope="col">Status</th>{% if manage_website_aliases %}<th scope="col">Actions</th>{% endif %}</tr>
</thead>
<tbody>
{% for alias in website_aliases %}
<tr>
<td class="domain">{{ alias.reservation.domain }}</td>
<td>
{% if alias.https_active %}HTTPS active{% elif alias.http_active %}HTTP active{% endif %}
{% if alias.state != "configured" %}
<div>{{ alias.get_operation_display }} · {{ alias.state|capfirst }}</div>
{% if manage_website_aliases and alias.problem %}<div>{{ alias.problem }}</div>{% endif %}
{% endif %}
</td>
{% if manage_website_aliases %}
<td>
{% if alias.finished_at %}
<div class="form-actions">
{% if alias.problem %}
{% if alias.operation != "https" or can_enable_alias_https %}
<a href="{% url 'panel:website_alias_action' account.pk alias.pk 'retry' %}">Retry</a>
{% endif %}
{% elif can_enable_alias_https and alias.http_active and not alias.https_active %}
<a href="{% url 'panel:website_alias_action' account.pk alias.pk 'https' %}">Enable HTTPS</a>
{% endif %}
<a href="{% url 'panel:website_alias_action' account.pk alias.pk 'remove' %}">Remove</a>
</div>
{% endif %}
</td>
{% endif %}
</tr>
{% endfor %}
</tbody>
</table>
</div>
{% else %}
<p class="empty">No website aliases.</p>
{% endif %}
</section>
@@ -0,0 +1,360 @@
import json
from pathlib import Path
from tempfile import TemporaryDirectory
from unittest.mock import patch
from django.contrib.auth import get_user_model
from django.contrib.auth.models import Permission
from django.core.exceptions import ValidationError
from django.db import IntegrityError
from django.db.models import ProtectedError
from django.test import SimpleTestCase, TestCase, override_settings
from django.urls import reverse
from django.utils import timezone
from coulobre import web_node_aliases, web_node_apply, web_node_tls
from coulobre.web_node import (
WebAlias,
WebAliasRequest,
WebSite,
parse_web_request,
)
from .models import (
HostingAccount,
Reseller,
WebActivation,
WebProvisioningPlan,
WebsiteAlias,
WebsiteDomain,
)
from .tasks import (
WEB_ACTIVATION_QUEUE,
WEB_HTTPS_QUEUE,
dispatch_web_activations,
dispatch_web_https,
enable_website_alias_https,
update_website_alias,
)
@override_settings(LOCAL_WEB_ACTIVATION=True, LOCAL_WEB_HTTPS=True)
class PanelWebsiteAliasTests(TestCase):
@classmethod
def setUpTestData(cls):
users = get_user_model().objects
cls.operator = users.create_superuser("operator")
cls.reseller = Reseller.objects.create(
user=users.create_user("reseller")
)
cls.account = HostingAccount.objects.create(
name="Managed website",
primary_domain="primary.example",
reseller=cls.reseller,
)
cls.other = HostingAccount.objects.create(
name="Other", primary_domain="other.example"
)
cls.site = WebSite(cls.account.pk, cls.account.primary_domain)
plan = WebProvisioningPlan.objects.create(
account=cls.account,
primary_domain=cls.site.domain,
completed_at=timezone.now(),
apache_config=cls.site.render("apache"),
)
WebActivation.objects.create(plan=plan, finished_at=timezone.now())
def setUp(self):
self.client.force_login(self.operator)
self.create_url = reverse(
"panel:website_alias_create", args=[self.account.pk]
)
self.account_url = self.account.get_absolute_url()
def create_alias(self, name="extra.example"):
self.assertRedirects(
self.client.post(self.create_url, {"domain": name}),
self.account_url,
)
return WebsiteAlias.objects.get()
def action(self, alias, verb, account=None):
return reverse(
"panel:website_alias_action",
args=[(account or self.account).pk, alias.pk, verb],
)
def test_alias_lifecycle_dispatches_http_and_https_to_their_workers(self):
alias = self.create_alias("Extra.Example.")
self.assertEqual(alias.reservation.domain, "extra.example")
target = WebAlias(self.site, alias.reservation.domain)
https = self.action(alias, "https")
self.assertContains(
self.client.post(https), "Wait for the current alias request"
)
with patch.object(update_website_alias, "apply_async") as publish:
dispatch_web_activations()
publish.assert_called_once_with(
args=[alias.pk], queue=WEB_ACTIVATION_QUEUE, retry=False
)
with patch(
"coulobre.hosting.tasks.update_local_website_alias"
) as node:
update_website_alias(alias.pk)
node.assert_called_once_with(target, "apply_alias")
self.assertContains(self.client.get(self.account_url), "HTTP active")
self.assertRedirects(self.client.post(https), self.account_url)
with patch.object(
enable_website_alias_https, "apply_async"
) as publish:
dispatch_web_https()
publish.assert_called_once_with(
args=[alias.pk], queue=WEB_HTTPS_QUEUE, retry=False
)
with (
patch("coulobre.hosting.tasks.enable_local_https") as enable,
patch("coulobre.hosting.tasks.update_local_website_alias") as http,
):
update_website_alias(alias.pk)
enable_website_alias_https(alias.pk)
http.assert_not_called()
enable.assert_called_once_with(target)
self.assertContains(self.client.get(self.account_url), "HTTPS active")
self.assertRedirects(
self.client.post(self.action(alias, "remove")), self.account_url
)
with patch(
"coulobre.hosting.tasks.update_local_website_alias"
) as node:
update_website_alias(alias.pk)
update_website_alias(alias.pk)
node.assert_called_once_with(target, "remove_alias")
self.assertFalse(
WebsiteDomain.objects.filter(domain=target.domain).exists()
)
self.assertFalse(WebsiteAlias.objects.exists())
self.assertTrue(
WebsiteDomain.objects.filter(
domain=self.site.domain, is_primary=True
).exists()
)
def test_primary_and_alias_hostnames_share_the_same_reservation(self):
conflict = self.client.post(
self.create_url, {"domain": self.other.primary_domain}
)
self.assertContains(conflict, "This domain is unavailable.")
alias = self.create_alias("Extra.Example")
conflict = self.client.post(
self.create_url, {"domain": "EXTRA.example."}
)
self.assertContains(conflict, "This domain is unavailable.")
with self.assertRaises(IntegrityError):
HostingAccount.objects.create(
name="Replacement", primary_domain=alias.reservation.domain
)
self.assertFalse(
HostingAccount.objects.filter(
primary_domain=alias.reservation.domain
).exists()
)
self.account.primary_domain = "new.example"
with self.assertRaisesMessage(
ValidationError, "Remove website aliases"
):
self.account.save(update_fields=["primary_domain"])
self.account.refresh_from_db()
self.assertEqual(self.account.primary_domain, self.site.domain)
def test_account_deletion_cannot_release_an_existing_alias(self):
alias = self.create_alias()
with self.assertRaises(ProtectedError):
self.account.delete()
self.assertTrue(WebsiteAlias.objects.filter(pk=alias.pk).exists())
def test_alias_cannot_be_added_to_an_unactivated_site(self):
other_url = reverse("panel:website_alias_create", args=[self.other.pk])
self.assertContains(
self.client.post(other_url, {"domain": "extra.example"}),
"Activate the website for the primary domain first.",
)
self.assertFalse(WebsiteAlias.objects.exists())
def test_alias_management_and_https_have_separate_permissions(self):
alias = self.create_alias()
WebsiteAlias.objects.filter(pk=alias.pk).update(
finished_at=timezone.now(),
http_active=True,
operation=WebsiteAlias.Operation.HTTPS,
problem="Certificate failed.",
)
worker = get_user_model().objects.create_user("limited")
worker.user_permissions.add(
*Permission.objects.filter(
codename__in=("view_hostingaccount", "manage_website_aliases")
)
)
self.client.force_login(worker)
self.assertEqual(
self.client.post(self.action(alias, "retry")).status_code, 403
)
self.assertEqual(
self.client.post(self.action(alias, "https")).status_code, 403
)
self.assertEqual(
self.client.get(
self.action(alias, "remove", self.other)
).status_code,
404,
)
self.client.force_login(self.reseller.user)
self.assertContains(
self.client.get(self.account_url), alias.reservation.domain
)
self.assertNotContains(
self.client.get(self.account_url), "Certificate failed."
)
self.assertEqual(
self.client.post(self.action(alias, "remove")).status_code, 403
)
class NodeWebsiteAliasTests(SimpleTestCase):
def setUp(self):
directory = Path(self.enterContext(TemporaryDirectory()))
self.state = directory / "state"
self.apache = directory / "sites-available"
self.enabled = directory / "sites-enabled"
for path in (self.state, self.apache, self.enabled):
path.mkdir()
(self.state / "apply.lock").touch()
self.site = WebSite(42, "primary.example")
self.alias = WebAlias(self.site, "Extra.Example.")
(self.state / "42.json").write_text(
json.dumps(self.site.manifest()), encoding="utf-8"
)
for key, value in (
("STATE_DIRECTORY", self.state),
("APACHE_AVAILABLE", self.apache),
("APACHE_ENABLED", self.enabled),
):
self.enterContext(patch.object(web_node_apply, key, value))
self.enterContext(
patch.object(web_node_apply.os, "geteuid", return_value=0)
)
self.enterContext(
patch.object(web_node_apply, "require_root_directory")
)
self.enterContext(patch.object(web_node_apply, "check_root_file"))
self.enterContext(patch.object(web_node_apply, "check_installation"))
def read(path, **kwargs):
return path.read_text(encoding="utf-8")
self.enterContext(
patch.object(web_node_apply, "read_root_file", side_effect=read)
)
self.enterContext(
patch.object(web_node_aliases, "read_root_file", side_effect=read)
)
self.enterContext(
patch.object(
web_node_aliases,
"require_root_directory",
side_effect=lambda path, create_mode=None: path.mkdir(
exist_ok=True
),
)
)
self.runner = self.enterContext(patch.object(web_node_apply, "run"))
def test_addition_replay_reuses_the_alias_configuration_and_reservation(
self,
):
request = WebAliasRequest(self.alias, "apply_alias")
self.assertEqual(parse_web_request(request.manifest()), request)
web_node_aliases.activate_alias(self.alias)
web_node_aliases.activate_alias(self.alias)
apache, enabled = web_node_aliases.alias_paths(self.alias)
self.assertEqual(enabled.resolve(), apache)
config = apache.read_text(encoding="utf-8")
self.assertIn("ServerName extra.example", config)
self.assertIn('DocumentRoot "/srv/coulobre/web/42/public"', config)
self.assertIn("/run/php/coulobre-42.sock", config)
self.assertEqual(
json.loads((self.state / "42.json").read_text()),
self.site.manifest(),
)
def test_primary_activation_and_aliases_reject_conflicting_hostnames(self):
other = WebSite(43, "other.example")
(self.state / "43.json").write_text(
json.dumps(other.manifest()), encoding="utf-8"
)
with self.assertRaisesMessage(
ValueError, "reserved as a primary domain"
):
web_node_aliases.activate_alias(WebAlias(self.site, other.domain))
web_node_aliases.activate_alias(self.alias)
with self.assertRaisesMessage(
ValueError, "reserved as another website alias"
):
web_node_aliases.activate_alias(WebAlias(other, self.alias.domain))
with self.assertRaisesMessage(
ValueError, "reserved as another website alias"
):
web_node_apply.reserve_account(
WebSite(44, self.alias.domain), "reserved", ()
)
def test_apache_hostname_collision_requires_an_unassigned_name(self):
self.runner.return_value = (
"VirtualHost configuration:\n"
"*:80 is a NameVirtualHost\n"
" port 80 namevhost unmanaged.example (/etc/apache2/site.conf:1)\n"
" wild alias *.example.net\n"
" alias extra.example\n"
)
for hostname in (
"unmanaged.example",
"alias.example.net",
self.alias.domain,
):
with (
self.subTest(hostname=hostname),
self.assertRaisesMessage(ValueError, "configured in Apache"),
):
web_node_aliases.activate_alias(WebAlias(self.site, hostname))
self.assertFalse(web_node_aliases.alias_marker(self.alias).exists())
def test_https_uses_the_alias_domain_and_dedicated_certificate(self):
with patch.object(web_node_tls.subprocess, "run") as certbot:
web_node_tls.request_certificate(self.alias)
command = certbot.call_args.args[0]
self.assertEqual(
command[-4:],
("--cert-name", self.alias.name, "--domains", self.alias.domain),
)
config = web_node_tls.render_https_configuration(self.alias)
self.assertIn("ServerName extra.example", config)
self.assertIn(f"/live/{self.alias.name}/fullchain.pem", config)
def test_failed_removal_restores_alias_links_before_returning(self):
web_node_aliases.activate_alias(self.alias)
apache, enabled = web_node_aliases.alias_paths(self.alias)
self.runner.side_effect = [ValueError("Config test failed."), ""]
with (
patch.object(
web_node_aliases, "delete_alias_certificate"
) as delete,
self.assertRaisesMessage(ValueError, "Config test failed."),
):
web_node_aliases.remove_alias(self.alias)
delete.assert_not_called()
self.assertEqual(enabled.resolve(), apache)
self.assertTrue(web_node_aliases.alias_marker(self.alias).is_file())
+10
View File
@@ -21,6 +21,16 @@ urlpatterns = [
"accounts/new/", views.AccountCreate.as_view(), name="account_create" "accounts/new/", views.AccountCreate.as_view(), name="account_create"
), ),
path("accounts/<int:pk>/", views.AccountDetail.as_view(), name="account"), path("accounts/<int:pk>/", views.AccountDetail.as_view(), name="account"),
path(
"accounts/<int:pk>/aliases/new/",
views.WebsiteAliasCreate.as_view(),
name="website_alias_create",
),
path(
"accounts/<int:pk>/aliases/<int:alias_pk>/<str:action>/",
views.WebsiteAliasAction.as_view(),
name="website_alias_action",
),
path( path(
"accounts/<int:pk>/measure-storage/", "accounts/<int:pk>/measure-storage/",
views.RequestSiteStorageMeasurement.as_view(), views.RequestSiteStorageMeasurement.as_view(),
+138 -7
View File
@@ -1,5 +1,6 @@
from operator import attrgetter from operator import attrgetter
from django import forms
from django.conf import settings from django.conf import settings
from django.contrib.auth import get_user_model from django.contrib.auth import get_user_model
from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.forms import UserCreationForm
@@ -85,6 +86,8 @@ from .models import (
WebActivation, WebActivation,
WebHTTPS, WebHTTPS,
WebProvisioningPlan, WebProvisioningPlan,
WebsiteAlias,
WebsiteDomain,
WebsiteRestoreJob, WebsiteRestoreJob,
) )
from .reseller_accounts import create_reseller_account from .reseller_accounts import create_reseller_account
@@ -107,6 +110,11 @@ from .web_node import (
build_web_smoke_bundle, build_web_smoke_bundle,
serialize_deployment_manifest, serialize_deployment_manifest,
) )
from .website_aliases import (
WebsiteAliasForm,
queue_alias_operation,
queue_website_alias,
)
VIEW_ACCOUNTS = "hosting.view_hostingaccount" VIEW_ACCOUNTS = "hosting.view_hostingaccount"
CHANGE_ACCOUNTS = "hosting.change_hostingaccount" CHANGE_ACCOUNTS = "hosting.change_hostingaccount"
@@ -147,6 +155,7 @@ COMPONENT_RESTORE_PERMISSIONS = {
), ),
} }
ACTIVATE_WEB = (VIEW_ACCOUNTS, VIEW_PLANS, "hosting.add_webactivation") ACTIVATE_WEB = (VIEW_ACCOUNTS, VIEW_PLANS, "hosting.add_webactivation")
MANAGE_WEBSITE_ALIASES = (VIEW_ACCOUNTS, "hosting.manage_website_aliases")
ENABLE_WEB_HTTPS = (VIEW_ACCOUNTS, VIEW_PLANS, "hosting.add_webhttps") ENABLE_WEB_HTTPS = (VIEW_ACCOUNTS, VIEW_PLANS, "hosting.add_webhttps")
PROVISION_DATABASE = ( PROVISION_DATABASE = (
VIEW_ACCOUNTS, VIEW_ACCOUNTS,
@@ -248,18 +257,18 @@ class AccountCreate(PermissionRequiredMixin, AccountEditor, CreateView):
def form_valid(self, form): def form_valid(self, form):
reseller = reseller_for_user(self.request.user) reseller = reseller_for_user(self.request.user)
if reseller is None:
return super().form_valid(form)
self.object = form.save(commit=False) self.object = form.save(commit=False)
try: try:
create_reseller_account(reseller, self.object) if reseller is None:
self.object.save()
else:
create_reseller_account(reseller, self.object)
except ValidationError as error: except ValidationError as error:
form.add_error(None, error) form.add_error(None, error)
return self.form_invalid(form) return self.form_invalid(form)
except IntegrityError: except IntegrityError:
if not HostingAccount.objects.filter( if not WebsiteDomain.objects.filter(
primary_domain=self.object.primary_domain domain=self.object.primary_domain
).exists(): ).exists():
raise raise
form.add_error("primary_domain", "This domain is unavailable.") form.add_error("primary_domain", "This domain is unavailable.")
@@ -279,7 +288,18 @@ class AccountEdit(
def form_valid(self, form): def form_valid(self, form):
self.object = form.save(commit=False) self.object = form.save(commit=False)
self.object.save(update_fields=form.changed_data) try:
self.object.save(update_fields=form.changed_data)
except ValidationError as error:
form.add_error(None, error)
return self.form_invalid(form)
except IntegrityError:
if not WebsiteDomain.objects.filter(
domain=self.object.primary_domain
).exists():
raise
form.add_error("primary_domain", "This domain is unavailable.")
return self.form_invalid(form)
return redirect(self.object) return redirect(self.object)
@@ -323,6 +343,19 @@ class AccountDetail(TenantScopeMixin, PermissionRequiredMixin, DetailView):
context["website_limit_pending"] = ( context["website_limit_pending"] = (
quota is not None and quota.finished_at is None quota is not None and quota.finished_at is None
) )
if settings.LOCAL_WEB_ACTIVATION:
context["website_aliases"] = (
WebsiteAlias.objects.filter(reservation__account=self.object)
.select_related("reservation")
.order_by("reservation__domain")
)
if not tenant and user.has_perms(MANAGE_WEBSITE_ALIASES):
context["manage_website_aliases"] = True
context["can_add_website_alias"] = site_is_active(self.object)
context["can_enable_alias_https"] = (
settings.LOCAL_WEB_HTTPS
and user.has_perms(ENABLE_WEB_HTTPS)
)
context["export_backup_manifest"] = not tenant and user.has_perms( context["export_backup_manifest"] = not tenant and user.has_perms(
EXPORT_BACKUP_MANIFEST EXPORT_BACKUP_MANIFEST
) )
@@ -470,6 +503,104 @@ class SiteStorageLimitEdit(
return redirect(self.account) return redirect(self.account)
class WebsiteAliasEditor(OperatorOnlyMixin, PermissionRequiredMixin, FormView):
permission_required = MANAGE_WEBSITE_ALIASES
template_name = "hosting/website_alias_form.html"
def dispatch(self, request, *args, **kwargs):
if not settings.LOCAL_WEB_ACTIVATION:
raise Http404
return super().dispatch(request, *args, **kwargs)
@cached_property
def account(self):
return get_object_or_404(HostingAccount, pk=self.kwargs["pk"])
def get_success_url(self):
return self.account.get_absolute_url()
def get_context_data(self, **kwargs):
return super().get_context_data(account=self.account, **kwargs)
class WebsiteAliasCreate(WebsiteAliasEditor):
form_class = WebsiteAliasForm
extra_context = {"title": "Add website alias", "submit_label": "Add alias"}
def form_valid(self, form):
try:
queue_website_alias(self.account.pk, form.cleaned_data["domain"])
except HostingAccount.DoesNotExist:
raise Http404 from None
except ValidationError as error:
form.add_error(None, error)
return self.form_invalid(form)
return super().form_valid(form)
class WebsiteAliasAction(WebsiteAliasEditor):
form_class = forms.Form
action_titles = {
"https": "Enable HTTPS",
"remove": "Remove alias",
"retry": "Retry alias request",
}
@property
def action(self):
value = self.kwargs["action"]
if value not in self.action_titles:
raise Http404
return value
@cached_property
def alias(self):
return get_object_or_404(
WebsiteAlias.objects.select_related("reservation"),
pk=self.kwargs["alias_pk"],
reservation__account=self.account,
)
def can_enable_https(self):
return settings.LOCAL_WEB_HTTPS and self.request.user.has_perms(
ENABLE_WEB_HTTPS
)
def has_permission(self):
if not super().has_permission():
return False
https = self.action == "https" or (
self.action == "retry"
and self.alias.operation == WebsiteAlias.Operation.HTTPS
)
return not https or self.can_enable_https()
def get_context_data(self, **kwargs):
title = self.action_titles[self.action]
return super().get_context_data(
alias=self.alias,
title=title,
submit_label=title,
action=self.action,
**kwargs,
)
def form_valid(self, form):
try:
queue_alias_operation(
self.account.pk,
self.alias.pk,
self.action,
allow_https=self.can_enable_https(),
)
except (HostingAccount.DoesNotExist, WebsiteAlias.DoesNotExist):
raise Http404 from None
except ValidationError as error:
form.add_error(None, error)
return self.form_invalid(form)
return super().form_valid(form)
class RequestSiteStorageMeasurement( class RequestSiteStorageMeasurement(
OperatorOnlyMixin, PermissionRequiredMixin, View OperatorOnlyMixin, PermissionRequiredMixin, View
): ):
+72
View File
@@ -0,0 +1,72 @@
from django import forms
from django.core.exceptions import PermissionDenied, ValidationError
from django.db import IntegrityError, transaction
from coulobre.web_node import WebAlias, WebSite
from .models import WebsiteAlias, WebsiteDomain
from .resource_requests import lock_hosting_account
from .sftp import site_is_active
class WebsiteAliasForm(forms.Form):
domain = forms.CharField(
label="Alias hostname",
max_length=253,
help_text=(
"Point this hostname's DNS to the same destination as the "
"primary domain."
),
)
@transaction.atomic
def queue_website_alias(account_id, domain):
account = lock_hosting_account(account_id, customer_id=None)
if not site_is_active(account):
raise ValidationError(
"Activate the website for the primary domain first."
)
try:
alias = WebAlias(WebSite(account.pk, account.primary_domain), domain)
except ValueError as error:
raise ValidationError({"domain": str(error)}) from error
try:
with transaction.atomic():
reservation = WebsiteDomain.objects.create(
account=account, domain=alias.domain
)
except IntegrityError:
if not WebsiteDomain.objects.filter(domain=alias.domain).exists():
raise
raise ValidationError(
{"domain": "This domain is unavailable."}
) from None
WebsiteAlias.objects.create(
reservation=reservation, primary_domain=account.primary_domain
)
@transaction.atomic
def queue_alias_operation(account_id, alias_id, operation, *, allow_https):
account = lock_hosting_account(account_id, customer_id=None)
aliases = WebsiteAlias.objects.filter(reservation__account=account)
alias = aliases.get(pk=alias_id)
if alias.finished_at is None:
raise ValidationError("Wait for the current alias request to finish.")
if operation == "retry":
if not alias.problem:
return
operation = alias.operation
if operation == WebsiteAlias.Operation.HTTPS:
if not allow_https:
raise PermissionDenied
if alias.https_active:
return
if not alias.http_active:
raise ValidationError("Activate the alias before enabling HTTPS.")
WebsiteAlias.objects.requeue(
aliases.filter(pk=alias.pk), operation=operation
)
+86 -3
View File
@@ -2,6 +2,7 @@ import argparse
import json import json
import sys import sys
from dataclasses import dataclass from dataclasses import dataclass
from hashlib import sha256
from importlib.resources import files from importlib.resources import files
from pathlib import Path from pathlib import Path
from string import Template from string import Template
@@ -68,15 +69,84 @@ class WebSite:
"socket_path": f"/run/php/{service_user}.sock", "socket_path": f"/run/php/{service_user}.sock",
} }
def render(self, configuration, *, port=80, tls_settings=""): def render(
self, configuration, *, port=80, tls_settings="", server_name=None
):
resource = files("coulobre.hosting").joinpath( resource = files("coulobre.hosting").joinpath(
"templates", "hosting", CONFIGURATIONS[configuration] "templates", "hosting", CONFIGURATIONS[configuration]
) )
values = self.configuration()
if server_name is not None:
values["domain"] = canonical_domain(server_name)
return Template(resource.read_text(encoding="utf-8")).substitute( return Template(resource.read_text(encoding="utf-8")).substitute(
self.configuration(), port=port, tls_settings=tls_settings values, port=port, tls_settings=tls_settings
) )
@dataclass(frozen=True)
class WebAlias:
site: WebSite
domain: str
def __post_init__(self):
if not isinstance(self.domain, str):
raise ValueError("Enter a valid website alias.")
domain = canonical_domain(self.domain)
if domain == self.site.domain:
raise ValueError("An alias must differ from the primary domain.")
object.__setattr__(self, "domain", domain)
@property
def name(self):
suffix = sha256(self.domain.encode("ascii")).hexdigest()[:24]
return f"coulobre-{self.site.account_id}-alias-{suffix}"
@classmethod
def from_manifest(cls, data):
if (
not isinstance(data, dict)
or data.keys() != {"version", "site", "domain"}
or type(data["version"]) is not int
or data["version"] != MANIFEST_VERSION
):
raise ValueError("Expected a website alias manifest.")
return cls(WebSite.from_manifest(data["site"]), data["domain"])
def manifest(self):
return {
"version": MANIFEST_VERSION,
"site": self.site.manifest(),
"domain": self.domain,
}
def render(self, configuration, *, port=80, tls_settings=""):
return self.site.render(
configuration,
port=port,
tls_settings=tls_settings,
server_name=self.domain,
)
@dataclass(frozen=True)
class WebAliasRequest:
alias: WebAlias
operation: str
def __post_init__(self):
if self.operation not in ("apply_alias", "remove_alias"):
raise ValueError("Expected a website alias operation.")
def manifest(self):
return {"operation": self.operation, "alias": self.alias.manifest()}
def parse_https_request(data):
if isinstance(data, dict) and "site" in data:
return WebAlias.from_manifest(data)
return WebSite.from_manifest(data)
@dataclass(frozen=True) @dataclass(frozen=True)
class WebStorageRequest: class WebStorageRequest:
site: WebSite site: WebSite
@@ -123,6 +193,10 @@ def parse_web_request(data):
return WebQuotaRequest( return WebQuotaRequest(
WebSite.from_manifest(data["site"]), data["limit_mib"] WebSite.from_manifest(data["site"]), data["limit_mib"]
) )
if isinstance(data, dict) and data.keys() == {"operation", "alias"}:
return WebAliasRequest(
WebAlias.from_manifest(data["alias"]), data["operation"]
)
return WebSite.from_manifest(data) return WebSite.from_manifest(data)
@@ -138,6 +212,15 @@ def apply_web_request(request):
apply_website_limit(request) apply_website_limit(request)
return None return None
if isinstance(request, WebAliasRequest):
from .web_node_aliases import activate_alias, remove_alias
if request.operation == "apply_alias":
activate_alias(request.alias)
else:
remove_alias(request.alias)
return None
from .web_node_apply import apply_site from .web_node_apply import apply_site
apply_site(request) apply_site(request)
@@ -244,7 +327,7 @@ def main(argv=None):
from .web_node_tls import provision_https from .web_node_tls import provision_https
return serve_apply_request( return serve_apply_request(
MANIFEST_VERSION, WebSite.from_manifest, provision_https MANIFEST_VERSION, parse_https_request, provision_https
) )
if args.command == "sftp-keys-request": if args.command == "sftp-keys-request":
+179
View File
@@ -0,0 +1,179 @@
import fcntl
import json
import os
import re
from fnmatch import fnmatchcase
from pathlib import Path
from . import web_node_apply as web
from .node_files import read_root_file, require_root_directory, write_new_file
from .web_node import WebAlias
from .web_node_tls import (
check_https_prerequisites,
delete_alias_certificate,
ensure_certificate,
install_https_configuration,
render_https_configuration,
)
APACHE_VHOST_NAME = re.compile(
r"^\s*(?:default server|port \d+ namevhost|\S+:\d+)\s+(\S+)\s+\("
)
APACHE_VHOST_ALIAS = re.compile(r"^\s*(?:wild )?alias\s+(\S+)(?:\s|$)")
def alias_directory():
return web.STATE_DIRECTORY / "aliases"
def alias_marker(alias):
return alias_directory() / f"{alias.name}.json"
def alias_paths(alias, *, https=False):
suffix = "-https" if https else ""
name = f"zz-{alias.name}{suffix}.conf"
return web.APACHE_AVAILABLE / name, web.APACHE_ENABLED / name
def read_alias(marker):
return WebAlias.from_manifest(
json.loads(read_root_file(marker, mode=0o600))
)
def check_alias_domain_available(domain, *, alias=None):
directory = alias_directory()
if not os.path.lexists(directory):
return
require_root_directory(directory)
for marker in directory.glob("*.json"):
current = read_alias(marker)
if current.domain == domain and current != alias:
raise ValueError(
"This domain is reserved as another website alias."
)
def check_apache_hostname_available(domain):
configuration = web.run("/usr/sbin/apache2ctl", "-S")
for line in configuration.splitlines():
match = APACHE_VHOST_NAME.match(line) or APACHE_VHOST_ALIAS.match(line)
if match and fnmatchcase(domain, match[1].rstrip(".").lower()):
raise ValueError("This hostname is already configured in Apache.")
def reserve_alias(alias):
for marker in web.STATE_DIRECTORY.glob("*.json"):
if json.loads(read_root_file(marker))["domain"] == alias.domain:
raise ValueError(
"This alias is already reserved as a primary domain."
)
require_root_directory(alias_directory(), create_mode=0o700)
check_alias_domain_available(alias.domain, alias=alias)
marker = alias_marker(alias)
if os.path.lexists(marker):
if read_alias(marker) != alias:
raise ValueError(
"The website alias reservation has a different identity."
)
return
if any(
os.path.lexists(path)
for paths in (alias_paths(alias), alias_paths(alias, https=True))
for path in paths
):
raise ValueError(
"The web node already has unmanaged files for this alias."
)
check_apache_hostname_available(alias.domain)
write_new_file(marker, json.dumps(alias.manifest()) + "\n", mode=0o600)
def activate_alias(alias):
if os.geteuid() != 0:
raise ValueError("Apply the website alias as root on the web node.")
with web.locked_web_node(fcntl.LOCK_EX):
web.check_reservation(alias.site)
web.check_installation(alias.site, web.SitePaths.for_site(alias.site))
reserve_alias(alias)
apache, enabled = alias_paths(alias)
with web.configuration_installation() as (created, reload_attempts):
web.install_configuration(apache, alias.render("apache"), created)
web.enable_apache_site(apache, enabled, created)
web.run("/usr/sbin/apache2ctl", "configtest")
reload_attempts.append("apache2")
web.run("/usr/sbin/service", "apache2", "reload")
def provision_alias_https(alias):
with web.locked_web_node(fcntl.LOCK_EX):
check_https_prerequisites(
alias.site, web.SitePaths.for_site(alias.site)
)
require_root_directory(alias_directory())
if read_alias(alias_marker(alias)) != alias:
raise ValueError(
"The website alias reservation has a different identity."
)
apache, enabled = alias_paths(alias)
web.check_configuration(apache, alias.render("apache"))
web.check_site_link(enabled, Path("../sites-available") / apache.name)
ensure_certificate(alias)
install_https_configuration(alias, *alias_paths(alias, https=True))
def remove_alias(alias):
if os.geteuid() != 0:
raise ValueError("Remove the website alias as root on the web node.")
with web.locked_web_node(fcntl.LOCK_EX):
web.check_reservation(alias.site)
for directory in (web.APACHE_AVAILABLE, web.APACHE_ENABLED):
require_root_directory(directory)
marker = alias_marker(alias)
paths = (alias_paths(alias), alias_paths(alias, https=True))
if not os.path.lexists(marker):
if any(os.path.lexists(path) for pair in paths for path in pair):
raise ValueError(
"The web node has unmanaged files for this alias."
)
return
require_root_directory(alias_directory())
if read_alias(marker) != alias:
raise ValueError(
"The website alias reservation has a different identity."
)
expected = (alias.render("apache"), render_https_configuration(alias))
links = []
for (apache, enabled), contents in zip(paths, expected, strict=True):
if os.path.lexists(apache):
web.check_configuration(apache, contents)
if os.path.lexists(enabled):
target = Path("../sites-available") / apache.name
web.check_site_link(enabled, target)
links.append((enabled, target))
disable_alias_vhosts(links)
for apache, _ in paths:
apache.unlink(missing_ok=True)
delete_alias_certificate(alias)
marker.unlink()
def disable_alias_vhosts(links):
removed = []
try:
for enabled, target in links:
enabled.unlink()
removed.append((enabled, target))
web.run("/usr/sbin/apache2ctl", "configtest")
web.run("/usr/sbin/service", "apache2", "reload")
except (OSError, ValueError, KeyboardInterrupt):
for enabled, target in removed:
enabled.symlink_to(target)
if removed:
web.run("/usr/sbin/service", "apache2", "reload")
raise
+4
View File
@@ -196,6 +196,10 @@ def reserve_account(site, user, paths):
"The primary domain is already reserved by another account." "The primary domain is already reserved by another account."
) )
from .web_node_aliases import check_alias_domain_available
check_alias_domain_available(site.domain)
if os.path.lexists(marker): if os.path.lexists(marker):
return return
if ( if (
+90 -24
View File
@@ -5,6 +5,7 @@ import subprocess
from pathlib import Path from pathlib import Path
from .node_files import check_root_file, require_root_directory from .node_files import check_root_file, require_root_directory
from .web_node import WebAlias
from .web_node_apply import ( from .web_node_apply import (
SitePaths, SitePaths,
check_configuration, check_configuration,
@@ -26,28 +27,38 @@ def provision_https(site):
if os.geteuid() != 0: if os.geteuid() != 0:
raise ValueError("Run https-request as root on the web node.") raise ValueError("Run https-request as root on the web node.")
if isinstance(site, WebAlias):
from .web_node_aliases import provision_alias_https
provision_alias_https(site)
return
with locked_web_node(fcntl.LOCK_SH): with locked_web_node(fcntl.LOCK_SH):
check_https_prerequisites(site, SitePaths.for_site(site)) check_https_prerequisites(site, SitePaths.for_site(site))
if not os.path.lexists(certbot_lineage(site)): ensure_certificate(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) enable_https(site)
def ensure_certificate(site):
if os.path.lexists(certbot_lineage(site)):
return
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)
def request_certificate(site): def request_certificate(site):
command = ( command = (
"/usr/bin/certbot", "/usr/bin/certbot",
@@ -93,13 +104,17 @@ def enable_https(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_https_prerequisites(site, paths) check_https_prerequisites(site, paths)
config = https_configuration(site) install_https_configuration(site, apache, enabled)
with configuration_installation() as (created, reload_attempts):
install_configuration(apache, config, created)
enable_apache_site(apache, enabled, created) def install_https_configuration(site, apache, enabled):
run("/usr/sbin/apache2ctl", "configtest") config = https_configuration(site)
reload_attempts.append("apache2") with configuration_installation() as (created, reload_attempts):
run("/usr/sbin/service", "apache2", "reload") 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 check_https_prerequisites(site, paths): def check_https_prerequisites(site, paths):
@@ -138,7 +153,12 @@ def https_paths(paths):
def certbot_lineage(site): def certbot_lineage(site):
return CERTBOT_ROOT / "live" / f"coulobre-{site.account_id}" name = (
site.name
if isinstance(site, WebAlias)
else f"coulobre-{site.account_id}"
)
return CERTBOT_ROOT / "live" / name
def https_configuration(site): def https_configuration(site):
@@ -185,6 +205,13 @@ def https_configuration(site):
str(chain_file), str(chain_file),
) )
return render_https_configuration(site)
def render_https_configuration(site):
lineage = certbot_lineage(site)
certificate = lineage / "fullchain.pem"
private_key = lineage / "privkey.pem"
return site.render( return site.render(
"apache", "apache",
port=443, port=443,
@@ -196,3 +223,42 @@ def https_configuration(site):
f' SSLCertificateKeyFile "{private_key}"\n' f' SSLCertificateKeyFile "{private_key}"\n'
), ),
) )
def delete_alias_certificate(alias):
lineage = certbot_lineage(alias)
renewal = CERTBOT_ROOT / "renewal" / f"{lineage.name}.conf"
archive = CERTBOT_ROOT / "archive" / lineage.name
if not any(os.path.lexists(path) for path in (lineage, renewal, archive)):
return
for directory in (lineage, archive):
if os.path.lexists(directory):
require_root_directory(directory)
if os.path.lexists(renewal):
require_root_directory(renewal.parent)
check_root_file(renewal)
try:
subprocess.run(
(
"/usr/bin/certbot",
"delete",
"--non-interactive",
"--cert-name",
lineage.name,
),
check=True,
stdin=subprocess.DEVNULL,
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
timeout=90,
env={"PATH": "/usr/sbin:/usr/bin:/sbin:/bin", "LANG": "C"},
)
except (
FileNotFoundError,
subprocess.TimeoutExpired,
subprocess.CalledProcessError,
):
raise ValueError(
"Certbot could not remove the alias certificate. "
"Check the Certbot log."
) from None