From bd88b64ca61f6188c4629421b5dec6fef05adcd3 Mon Sep 17 00:00:00 2001 From: Peter van Arkel Date: Sun, 22 Nov 2026 12:06:10 +0100 Subject: [PATCH 1/3] Give independent websites separate node and archive identities --- src/coulobre/account_backup.py | 43 ++++++++++++++++++++- src/coulobre/web_node.py | 58 ++++++++++++++++++++-------- src/coulobre/web_node_access.py | 19 ++++++++- src/coulobre/web_node_apply.py | 21 ++++++---- src/coulobre/web_node_retirement.py | 60 +++++++++++++++++++++++------ src/coulobre/web_node_runtime.py | 2 +- src/coulobre/web_node_sftp.py | 7 ++++ src/coulobre/web_node_tls.py | 6 +-- 8 files changed, 170 insertions(+), 46 deletions(-) diff --git a/src/coulobre/account_backup.py b/src/coulobre/account_backup.py index 26a144c..be1f78f 100644 --- a/src/coulobre/account_backup.py +++ b/src/coulobre/account_backup.py @@ -18,6 +18,7 @@ from .web_node import WebSite BASE_MANIFEST_VERSION = 1 MAIL_MANIFEST_VERSION = 2 +MULTI_SITE_MANIFEST_VERSION = 3 MANIFEST_KIND = "coulobre_account_backup" MANIFEST_NAME = "manifest.json" MAX_MANIFEST_BYTES = 1024 * 1024 @@ -29,8 +30,27 @@ class AccountBackup: website: WebSite databases: tuple[DatabaseSpec, ...] mailboxes: tuple[MailboxSpec, ...] | None = None + additional_websites: tuple[WebSite, ...] = () def __post_init__(self): + if self.website.site_id is not None: + raise ValueError( + "The primary website must use its account identity." + ) + sites = {self.website.domain} + site_ids = set() + for site in self.additional_websites: + if ( + site.account_id != self.website.account_id + or site.site_id is None + ): + raise ValueError( + "All websites must belong to the backup account." + ) + if site.domain in sites or site.site_id in site_ids: + raise ValueError("The account backup lists a website twice.") + sites.add(site.domain) + site_ids.add(site.site_id) names = set() for database in self.databases: if database.account_id != self.website.account_id: @@ -57,6 +77,11 @@ class AccountBackup: manifest["mailboxes"] = [ mailbox.manifest() for mailbox in self.mailboxes ] + if self.additional_websites: + manifest["version"] = MULTI_SITE_MANIFEST_VERSION + manifest["additional_websites"] = [ + site.manifest() for site in self.additional_websites + ] return manifest @classmethod @@ -67,30 +92,44 @@ class AccountBackup: if type(version) is not int or version not in ( BASE_MANIFEST_VERSION, MAIL_MANIFEST_VERSION, + MULTI_SITE_MANIFEST_VERSION, ): raise ValueError("Unsupported account backup manifest version.") fields = {"version", "kind", "website", "databases"} - if version == MAIL_MANIFEST_VERSION: + if version == MULTI_SITE_MANIFEST_VERSION: + fields.add("additional_websites") + if version == MAIL_MANIFEST_VERSION or ( + version == MULTI_SITE_MANIFEST_VERSION and "mailboxes" in data + ): fields.add("mailboxes") if data.keys() != fields or not isinstance(data["databases"], list): raise ValueError("Expected a Coulobre account backup manifest.") mailboxes = None - if version == MAIL_MANIFEST_VERSION: + if "mailboxes" in fields: if not isinstance(data["mailboxes"], list): raise ValueError("Expected a list of mailbox manifests.") mailboxes = tuple( MailboxSpec.from_manifest(item) for item in data["mailboxes"] ) + sites = data.get("additional_websites", []) + if not isinstance(sites, list): + raise ValueError( + "Expected a list of additional website manifests." + ) return cls( WebSite.from_manifest(data["website"]), tuple( DatabaseSpec.from_manifest(item) for item in data["databases"] ), mailboxes, + tuple(WebSite.from_manifest(site) for site in sites), ) def components(self): yield self.website, "website.json", "website.tar.gz" + for site in self.additional_websites: + name = f"websites/{site.node_key}" + yield site, f"{name}.json", f"{name}.tar.gz" for database in self.databases: name = f"database-{database.suffix}" yield database, f"{name}.json", f"{name}.sql.gz" diff --git a/src/coulobre/web_node.py b/src/coulobre/web_node.py index 2a82cf6..3a98c9a 100644 --- a/src/coulobre/web_node.py +++ b/src/coulobre/web_node.py @@ -16,6 +16,7 @@ from .php_runtime import validate_php_version, validate_php_versions from .service_access import ServiceAccessRequest, parse_service_request MANIFEST_VERSION = 1 +INDEPENDENT_SITE_VERSION = 2 MAX_STORAGE_BYTES = 2**63 - 1 MAX_STORAGE_LIMIT_MIB = 2**31 - 1 CONFIGURATIONS = { @@ -28,6 +29,7 @@ CONFIGURATIONS = { class WebSite: account_id: int domain: str + site_id: int | None = None def __post_init__(self): if ( @@ -37,40 +39,62 @@ class WebSite: raise ValueError( "The account ID must be a positive 64-bit integer." ) + if self.site_id is not None and ( + type(self.site_id) is not int or not 1 <= self.site_id <= 2**63 - 1 + ): + raise ValueError("The site 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)) + @property + def node_key(self): + return ( + str(self.account_id) + if self.site_id is None + else f"s{self.site_id}" + ) + + @property + def service_user(self): + return f"coulobre-{self.node_key}" + @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: + if not isinstance(data, dict): + raise ValueError("Expected a website manifest.") + version = data.get("version") + if type(version) is not int or version not in ( + MANIFEST_VERSION, + INDEPENDENT_SITE_VERSION, + ): raise ValueError("Unsupported web deployment manifest version.") - return cls(data["account_id"], data["domain"]) + fields = {"version", "account_id", "domain"} + if version == INDEPENDENT_SITE_VERSION: + fields.add("site_id") + if data.keys() != fields or ( + version == INDEPENDENT_SITE_VERSION and data["site_id"] is None + ): + raise ValueError("Expected a website manifest.") + return cls(data["account_id"], data["domain"], data.get("site_id")) def manifest(self): - return { + data = { "version": MANIFEST_VERSION, "account_id": self.account_id, "domain": self.domain, } + if self.site_id is not None: + data.update(version=INDEPENDENT_SITE_VERSION, site_id=self.site_id) + return data 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", + "service_user": self.service_user, + "document_root": f"/srv/coulobre/web/{self.node_key}/public", + "socket_path": f"/run/php/{self.service_user}.sock", } def render( @@ -119,7 +143,7 @@ class WebAlias: @property def name(self): suffix = sha256(self.domain.encode("ascii")).hexdigest()[:24] - return f"coulobre-{self.site.account_id}-alias-{suffix}" + return f"{self.site.service_user}-alias-{suffix}" @classmethod def from_manifest(cls, data): diff --git a/src/coulobre/web_node_access.py b/src/coulobre/web_node_access.py index f5b7584..ea8d6ee 100644 --- a/src/coulobre/web_node_access.py +++ b/src/coulobre/web_node_access.py @@ -9,6 +9,14 @@ APACHE_CONFIG = Path("/etc/apache2/conf-enabled") SSH_CONFIG = Path("/etc/ssh/sshd_config.d") +def website_suspension_path(site): + return APACHE_CONFIG / f"coulobre-suspended-{site.node_key}.conf" + + +def sftp_suspension_path(site): + return SSH_CONFIG / f"01-coulobre-suspended-{site.node_key}.conf" + + def set_website_access(site, suspended): document_root = site.configuration()["document_root"] # The shared ACME webroot is outside the hosted document root. @@ -17,17 +25,24 @@ def set_website_access(site, suspended): " Require all denied\n" "\n" ) - path = APACHE_CONFIG / f"coulobre-suspended-{site.account_id}.conf" + path = website_suspension_path(site) def validate(): web.run("/usr/sbin/apache2ctl", "configtest") set_configuration(site, suspended, path, config, validate, "apache2") + if site.site_id is not None: + from .web_node_sftp import AUTHORIZED_KEYS + + if os.path.lexists( + AUTHORIZED_KEYS / site.service_user + ) or os.path.lexists(sftp_suspension_path(site)): + set_sftp_access(site, suspended) def set_sftp_access(site, suspended): user = site.configuration()["service_user"] - path = SSH_CONFIG / f"01-coulobre-suspended-{site.account_id}.conf" + path = sftp_suspension_path(site) def validate(): configuration = web.run( diff --git a/src/coulobre/web_node_apply.py b/src/coulobre/web_node_apply.py index f528ee0..5648f36 100644 --- a/src/coulobre/web_node_apply.py +++ b/src/coulobre/web_node_apply.py @@ -54,7 +54,7 @@ class SitePaths: def for_site(cls, site, *, version=None, archived_account=None): configuration = site.configuration() name = configuration["service_user"] - account = WEB_ROOT / str(site.account_id) + account = WEB_ROOT / site.node_key socket = Path(configuration["socket_path"]) runtime = DEFAULT_PHP_RUNTIME route = (archived_account or account) / ".coulobre-php.sock" @@ -132,7 +132,7 @@ def install_site(site, *, php_settings=None, allowed=()): create_route = not ( paths.routed or ( - os.path.lexists(STATE_DIRECTORY / f"{site.account_id}.json") + os.path.lexists(STATE_DIRECTORY / f"{site.node_key}.json") and (os.path.lexists(paths.apache) or os.path.lexists(paths.pool)) ) ) @@ -171,7 +171,7 @@ def site_status(site): require_root_directory(STATE_DIRECTORY) except FileNotFoundError: return report - marker = STATE_DIRECTORY / f"{site.account_id}.json" + marker = STATE_DIRECTORY / f"{site.node_key}.json" if not os.path.lexists(marker): return report @@ -195,7 +195,7 @@ def site_status(site): def check_reservation(site): - marker = STATE_DIRECTORY / f"{site.account_id}.json" + marker = STATE_DIRECTORY / f"{site.node_key}.json" try: saved = json.loads(read_root_file(marker)) except FileNotFoundError: @@ -208,7 +208,7 @@ def check_reservation(site): def site_storage(site): check_reservation(site) - account = WEB_ROOT / str(site.account_id) + account = WEB_ROOT / site.node_key require_root_directory(account) user = site.configuration()["service_user"] uid, gid = check_system_account(user, account) @@ -254,7 +254,7 @@ def check_services(runtime): def reserve_account(site, user, paths): - marker = STATE_DIRECTORY / f"{site.account_id}.json" + marker = STATE_DIRECTORY / f"{site.node_key}.json" if os.path.lexists(marker.with_suffix(".retired")): raise ValueError("This website belongs to a retired hosting account.") manifest = site.manifest() @@ -263,7 +263,7 @@ def reserve_account(site, user, paths): if existing == marker: if saved != manifest: raise ValueError( - "The account is already reserved with a different " + "The website is already reserved with a different " "manifest." ) elif saved["domain"] == site.domain: @@ -271,7 +271,10 @@ def reserve_account(site, user, paths): "The primary domain is already reserved by another account." ) - from .web_node_aliases import check_alias_domain_available + from .web_node_aliases import ( + check_alias_domain_available, + check_apache_hostname_available, + ) check_alias_domain_available(site.domain) @@ -285,6 +288,8 @@ def reserve_account(site, user, paths): raise ValueError( "The web node already has unmanaged resources for this account." ) + if site.site_id is not None: + check_apache_hostname_available(site.domain) write_new_file(marker, json.dumps(manifest) + "\n", mode=0o600) diff --git a/src/coulobre/web_node_retirement.py b/src/coulobre/web_node_retirement.py index 15bc317..42ddd4e 100644 --- a/src/coulobre/web_node_retirement.py +++ b/src/coulobre/web_node_retirement.py @@ -30,14 +30,21 @@ def retire_site(request): retirement = RetirementRecord(web.STATE_DIRECTORY, request) if retirement.is_complete: return - reservation = web.STATE_DIRECTORY / f"{site.account_id}.json" + reservation = web.STATE_DIRECTORY / f"{site.node_key}.json" started = retirement.matches(retirement.started) + if ( + site.site_id is not None + and not os.path.lexists(reservation) + and not (retirement.directory / "site").is_file() + ): + retire_unprovisioned_site(site, reservation, retirement) + return if os.path.lexists(reservation) or not started: web.check_reservation(site) elif not (retirement.directory / "site").is_file(): raise ValueError("The original website reservation is missing.") archived_account = web.WEB_ROOT / ".retired" / request.operation_id - account = web.WEB_ROOT / str(site.account_id) + account = web.WEB_ROOT / site.node_key paths = web.SitePaths.for_site( site, archived_account=archived_account @@ -67,13 +74,45 @@ def retire_site(request): apache = managed_vhosts(site, paths) retirement.begin() detach_site(site, paths, key_file, apache, retirement) - marker = reservation.with_suffix(".retired") - if not os.path.lexists(marker): - write_new_file(marker, retirement.document, mode=0o600) - elif read_root_file(marker, mode=0o600) != retirement.document: - raise ValueError("The website has a different retirement record.") - archive_path(reservation, retirement.directory / "site") - retirement.finish() + finish_site_retirement(reservation, retirement) + + +def retire_unprovisioned_site(site, reservation, retirement): + paths = web.SitePaths.for_site(site) + https, enabled = https_paths(paths) + if ( + web.current_user(site.service_user) + or web.current_group(site.service_user) + or any( + os.path.lexists(path) + for path in ( + paths.account, + paths.apache, + paths.enabled, + paths.pool, + paths.socket, + https, + enabled, + AUTHORIZED_KEYS / site.service_user, + ) + ) + ): + raise ValueError( + "The web node has unmanaged resources for this website." + ) + check_aliases(site) + retirement.begin() + finish_site_retirement(reservation, retirement) + + +def finish_site_retirement(reservation, retirement): + marker = reservation.with_suffix(".retired") + if not os.path.lexists(marker): + write_new_file(marker, retirement.document, mode=0o600) + elif read_root_file(marker, mode=0o600) != retirement.document: + raise ValueError("The website has a different retirement record.") + archive_path(reservation, retirement.directory / "site") + retirement.finish() def check_aliases(site): @@ -82,8 +121,7 @@ def check_aliases(site): return require_root_directory(directory) if any( - read_alias(marker).site.account_id == site.account_id - for marker in directory.glob("*.json") + read_alias(marker).site == site for marker in directory.glob("*.json") ): raise ValueError( "Remove the managed website aliases before retiring the site." diff --git a/src/coulobre/web_node_runtime.py b/src/coulobre/web_node_runtime.py index 966137d..6c6b587 100644 --- a/src/coulobre/web_node_runtime.py +++ b/src/coulobre/web_node_runtime.py @@ -32,7 +32,7 @@ def switch_php_version(site, version): raise ValueError( f"Install stable PHP {version} FPM on the web node." ) - if current.socket.name == f"coulobre-{site.account_id}.sock" and ( + if current.socket.name == f"{site.service_user}.sock" and ( current.routed or current.runtime.version != version ): current = route_legacy_site(site, current) diff --git a/src/coulobre/web_node_sftp.py b/src/coulobre/web_node_sftp.py index e231139..e5165dc 100644 --- a/src/coulobre/web_node_sftp.py +++ b/src/coulobre/web_node_sftp.py @@ -37,6 +37,13 @@ def apply_sftp_keys(request): target = AUTHORIZED_KEYS / user with locked_web_node(fcntl.LOCK_EX): + if site.site_id is not None: + from .web_node_access import website_suspension_path + + if os.path.lexists(website_suspension_path(site)): + raise ValueError( + "Resume the website before changing SFTP keys." + ) check_reservation(site) if os.path.lexists(target): check_root_file(target, mode=0o644) diff --git a/src/coulobre/web_node_tls.py b/src/coulobre/web_node_tls.py index 8edacdb..0486405 100644 --- a/src/coulobre/web_node_tls.py +++ b/src/coulobre/web_node_tls.py @@ -158,11 +158,7 @@ def https_paths(paths): def certbot_lineage(site): - name = ( - site.name - if isinstance(site, WebAlias) - else f"coulobre-{site.account_id}" - ) + name = site.name if isinstance(site, WebAlias) else site.service_user return CERTBOT_ROOT / "live" / name -- 2.43.0 From 86d91303d4233999f5a4cc211c4079b87d19a7f4 Mon Sep 17 00:00:00 2001 From: Peter van Arkel Date: Sun, 22 Nov 2026 12:06:10 +0100 Subject: [PATCH 2/3] Manage independent websites and their account lifecycle --- src/coulobre/hosting/account_backup_forms.py | 14 ++ src/coulobre/hosting/account_backups.py | 2 + src/coulobre/hosting/account_retirement.py | 9 +- src/coulobre/hosting/admin.py | 1 + src/coulobre/hosting/backup_restores.py | 41 +++- .../hosting/independent_website_views.py | 202 ++++++++++++++++++ src/coulobre/hosting/independent_websites.py | 195 +++++++++++++++++ .../migrations/0047_independent_websites.py | 106 +++++++++ src/coulobre/hosting/models.py | 53 ++++- src/coulobre/hosting/service_changes.py | 22 +- src/coulobre/hosting/tasks.py | 44 +++- .../hosting/account_backup_archive_table.html | 4 +- .../templates/hosting/account_detail.html | 4 + .../hosting/independent_website_form.html | 24 +++ .../hosting/independent_websites.html | 44 ++++ .../templates/hosting/website_restore.html | 2 +- src/coulobre/hosting/urls.py | 20 ++ src/coulobre/hosting/views.py | 55 ++++- 18 files changed, 820 insertions(+), 22 deletions(-) create mode 100644 src/coulobre/hosting/independent_website_views.py create mode 100644 src/coulobre/hosting/independent_websites.py create mode 100644 src/coulobre/hosting/migrations/0047_independent_websites.py create mode 100644 src/coulobre/hosting/templates/hosting/independent_website_form.html create mode 100644 src/coulobre/hosting/templates/hosting/independent_websites.html diff --git a/src/coulobre/hosting/account_backup_forms.py b/src/coulobre/hosting/account_backup_forms.py index 6032564..7257a0b 100644 --- a/src/coulobre/hosting/account_backup_forms.py +++ b/src/coulobre/hosting/account_backup_forms.py @@ -91,6 +91,18 @@ class WebsiteRestoreForm(BackupRestoreForm): label="Replace the existing file at this path", required=False ) + def __init__(self, *args, targets=None, **kwargs): + super().__init__(*args, **kwargs) + self.targets = targets or {} + if len(self.targets) > 1: + self.fields["site_key"] = forms.ChoiceField( + label="Website", + choices=[ + (key, site.domain) for key, site in self.targets.items() + ], + ) + self.order_fields(["site_key", "scope", "filename", "replace"]) + def clean_filename(self): filename = self.cleaned_data["filename"] if filename: @@ -102,6 +114,8 @@ class WebsiteRestoreForm(BackupRestoreForm): def clean(self): cleaned = super().clean() + if len(self.targets) == 1: + cleaned["site_key"] = next(iter(self.targets)) if cleaned.get("scope") == "file" and cleaned.get("filename") == "": self.add_error( "filename", "Enter the path of the file to restore." diff --git a/src/coulobre/hosting/account_backups.py b/src/coulobre/hosting/account_backups.py index c618a2b..26390be 100644 --- a/src/coulobre/hosting/account_backups.py +++ b/src/coulobre/hosting/account_backups.py @@ -8,6 +8,7 @@ from django.utils import timezone from coulobre.account_backup import AccountBackup from coulobre.web_node import WebSite +from .independent_websites import active_websites from .models import ( AccountBackupSchedule, HostingAccount, @@ -34,6 +35,7 @@ def account_backup_manifest(account, *, include_mailboxes=False): WebSite(account.pk, account.primary_domain), tuple(database.spec for database in account.databases.all()), mailboxes, + tuple(site.spec for site in active_websites(account)), ).manifest() diff --git a/src/coulobre/hosting/account_retirement.py b/src/coulobre/hosting/account_retirement.py index b1cb166..6a84776 100644 --- a/src/coulobre/hosting/account_retirement.py +++ b/src/coulobre/hosting/account_retirement.py @@ -13,6 +13,7 @@ from coulobre.node_retirement import RetirementRequest from coulobre.sftp_keys import public_key_fingerprint from coulobre.web_node import WebAlias, WebSite +from .independent_websites import active_websites from .models import ( AccountBackupExpiration, AccountRetirement, @@ -83,6 +84,10 @@ def account_inventory(account): .distinct() ) certificates.extend(tls_domains) + additional = list(active_websites(account)) + certificates.extend( + site.spec.domain for site in additional if site.https_enabled + ) sftp = getattr(account, "sftp", None) site_domains = WebActivation.objects.filter( plan__account=account, finished_at__isnull=False, problem="" @@ -101,7 +106,9 @@ def account_inventory(account): "site": website.manifest(), "aliases": [domain for domain, _ in aliases], "certificates": sorted(set(certificates)), - "website_domains": sorted(set(site_domains)), + "website_domains": sorted( + set(site_domains) | {site.spec.domain for site in additional} + ), "sftp_keys": sorted( public_key_fingerprint(key) for key in sftp.public_keys.splitlines() diff --git a/src/coulobre/hosting/admin.py b/src/coulobre/hosting/admin.py index 9763dc7..f6f3993 100644 --- a/src/coulobre/hosting/admin.py +++ b/src/coulobre/hosting/admin.py @@ -59,6 +59,7 @@ class HostingPlanAdmin(admin.ModelAdmin): list_display = ( "name", "description", + "website_limit", "database_limit", "mailbox_limit", "mailbox_quota_mib", diff --git a/src/coulobre/hosting/backup_restores.py b/src/coulobre/hosting/backup_restores.py index 84f1418..a213133 100644 --- a/src/coulobre/hosting/backup_restores.py +++ b/src/coulobre/hosting/backup_restores.py @@ -5,6 +5,7 @@ from django.db import transaction from coulobre.account_backup import AccountBackup from coulobre.web_node import WebSite +from .independent_websites import Operation, active_websites from .models import ComponentRestoreJob, HostingMailbox, WebsiteRestoreJob from .resource_requests import lock_hosting_account, require_active_services @@ -50,16 +51,40 @@ def available_restore_resources(backup, kind, current): return {key: spec for key, spec in current.items() if key in keys} +def current_website_restore_targets(account): + if account.retired_at is not None: + return {} + sites = [WebSite(account.pk, account.primary_domain)] + sites.extend( + website.spec + for website in active_websites(account).exclude( + operation=Operation.RETIRE, finished_at__isnull=True + ) + ) + return {site.node_key: site for site in sites} + + +def available_website_restore_targets(backup, current=None): + if current is None: + current = current_website_restore_targets(backup.account) + return { + key: site + for key, site in current.items() + if backup.can_restore_website(site) + } + + @transaction.atomic def queue_website_restore( - backup, *, restore_id, filename, replace, operator_username + backup, *, restore_id, filename, replace, operator_username, site_key=None ): account = lock_hosting_account(backup.account_id, customer_id=None) require_active_services(account) backup.refresh_from_db() - if not backup.can_restore_website( - WebSite(account.pk, account.primary_domain) - ): + backup.account = account + targets = available_website_restore_targets(backup) + site = targets.get(site_key or str(account.pk)) + if site is None: raise ValidationError( "Choose a completed backup of the current website." ) @@ -69,7 +94,13 @@ def queue_website_restore( backup, restore_id, operator_username, - {"filename": filename, "replace": replace}, + { + "filename": filename, + "replace": replace, + "site_manifest": site.manifest() + if site.site_id is not None + else None, + }, WebsiteRestoreJob.objects.filter( backup__account=account, finished_at__isnull=True ), diff --git a/src/coulobre/hosting/independent_website_views.py b/src/coulobre/hosting/independent_website_views.py new file mode 100644 index 0000000..c77d68c --- /dev/null +++ b/src/coulobre/hosting/independent_website_views.py @@ -0,0 +1,202 @@ +from django import forms +from django.conf import settings +from django.contrib.auth.mixins import PermissionRequiredMixin +from django.core.exceptions import ValidationError +from django.db import IntegrityError +from django.http import Http404, JsonResponse +from django.shortcuts import get_object_or_404, redirect +from django.utils.functional import cached_property +from django.views import View +from django.views.generic import FormView +from django.views.generic.detail import SingleObjectMixin + +from coulobre.domain_names import canonical_domain + +from .access import OperatorOnlyMixin, TenantScopeMixin +from .independent_websites import ( + Operation, + account_websites, + allowed_versions, + create_website, + queue_website_operation, +) +from .models import HostingAccount, IndependentWebsite, WebsiteDomain + + +class WebsiteCreateForm(forms.Form): + domain = forms.CharField(max_length=253) + php_version = forms.CharField( + label="PHP series", + required=False, + max_length=5, + help_text="Leave blank to use the newest allowed stable series.", + ) + + def clean_domain(self): + try: + return canonical_domain(self.cleaned_data["domain"]) + except ValueError as error: + raise forms.ValidationError(str(error)) from error + + +class WebsiteOperationForm(forms.Form): + def __init__(self, *args, operation, domain, **kwargs): + super().__init__(*args, **kwargs) + self.operation = operation + self.domain = domain + if operation in (Operation.ACTIVATE, Operation.PHP): + self.fields["php_version"] = forms.CharField( + label="PHP series", + max_length=5, + required=operation == Operation.PHP, + ) + if operation == Operation.RETIRE: + self.fields["confirmation"] = forms.CharField( + label="Confirm the website domain", + max_length=253, + help_text=f"Enter {domain} to retire this website.", + ) + + def clean_confirmation(self): + value = self.cleaned_data["confirmation"] + if value != self.domain: + raise forms.ValidationError("Enter the website domain exactly.") + return value + + +class IndependentWebsiteEditor( + TenantScopeMixin, PermissionRequiredMixin, SingleObjectMixin, FormView +): + queryset = HostingAccount.objects.filter( + retired_at__isnull=True + ).select_related("hosting_plan") + object = None + customer_relation = "customer" + permission_required = ( + "hosting.view_hostingaccount", + "hosting.change_hostingaccount", + ) + template_name = "hosting/independent_website_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 self.get_object() + + def get_context_data(self, **kwargs): + return super().get_context_data( + account=self.account, + allowed_php_versions=allowed_versions(self.account), + **kwargs, + ) + + +class IndependentWebsiteCreate(IndependentWebsiteEditor): + form_class = WebsiteCreateForm + extra_context = {"title": "Add independent website", "add": True} + + def form_valid(self, form): + domain = form.cleaned_data["domain"] + try: + create_website( + self.account.pk, + domain, + form.cleaned_data["php_version"], + self.request.user, + ) + except HostingAccount.DoesNotExist as error: + raise Http404 from error + except ValidationError as error: + form.add_error(None, error) + return self.form_invalid(form) + except IntegrityError: + if not WebsiteDomain.objects.filter(domain=domain).exists(): + raise + form.add_error("domain", "This domain is unavailable.") + return self.form_invalid(form) + return redirect(self.account) + + +class IndependentWebsiteOperation(IndependentWebsiteEditor): + form_class = WebsiteOperationForm + + @cached_property + def operation(self): + try: + operation = Operation(self.kwargs["operation"]) + except ValueError: + raise Http404 from None + if operation == Operation.HTTPS and not settings.LOCAL_WEB_HTTPS: + raise Http404 + return operation + + @cached_property + def website(self): + return get_object_or_404( + account_websites(self.account), + pk=self.kwargs["site_pk"], + retired_at__isnull=True, + ) + + def get_initial(self): + return {"php_version": self.website.requested_php_version} + + def get_form_kwargs(self): + return super().get_form_kwargs() | { + "operation": self.operation, + "domain": self.website.reservation.domain, + } + + def get_context_data(self, **kwargs): + return super().get_context_data( + title=self.operation.label, + website=self.website, + retiring=self.operation == Operation.RETIRE, + **kwargs, + ) + + def form_valid(self, form): + try: + queue_website_operation( + self.account.pk, + self.website.pk, + self.operation, + form.cleaned_data.get("php_version", ""), + self.request.user, + ) + except (HostingAccount.DoesNotExist, IndependentWebsite.DoesNotExist): + raise Http404 from None + except ValidationError as error: + if self.operation == Operation.ACTIVATE: + form.add_error(None, " ".join(error.messages)) + else: + form.add_error(None, error) + return self.form_invalid(form) + return redirect(self.account) + + +class IndependentWebsiteManifest( + OperatorOnlyMixin, PermissionRequiredMixin, View +): + permission_required = "hosting.view_hostingaccount" + + def get(self, request, pk, site_pk): + website = get_object_or_404( + IndependentWebsite.objects.select_related("reservation"), + pk=site_pk, + reservation__account_id=pk, + ) + return JsonResponse( + website.spec.manifest(), + headers={ + "Cache-Control": "private, no-store", + "Content-Disposition": ( + "attachment; " + f'filename="coulobre-website-{website.pk}.json"' + ), + }, + ) diff --git a/src/coulobre/hosting/independent_websites.py b/src/coulobre/hosting/independent_websites.py new file mode 100644 index 0000000..65e6e98 --- /dev/null +++ b/src/coulobre/hosting/independent_websites.py @@ -0,0 +1,195 @@ +from django.conf import settings +from django.core.exceptions import PermissionDenied, ValidationError +from django.db import transaction +from django.utils import timezone + +from coulobre.node_retirement import RetirementRequest +from coulobre.php_pool_settings import PhpPoolSettings +from coulobre.php_runtime import validate_php_version +from coulobre.service_access import ServiceAccessRequest + +from .access import is_tenant, manages_account +from .models import IndependentWebsite, WebsiteDomain, WebsiteRestoreJob +from .node_client import ( + activate_local_site, + apply_on_local_node, + enable_local_https, + set_local_site_storage_limit, + update_local_php_version, +) +from .resource_requests import lock_hosting_account, require_active_services + +Operation = IndependentWebsite.Operation + + +def account_websites(account): + return ( + IndependentWebsite.objects.filter(reservation__account=account) + .select_related("reservation") + .order_by("reservation__domain") + ) + + +def active_websites(account): + return account_websites(account).filter( + activated=True, retired_at__isnull=True + ) + + +def website_limit(account): + plan = account.hosting_plan + return plan.website_limit if plan is not None else 1 + + +def allowed_versions(account): + plan = account.hosting_plan + return plan.allowed_php_versions() if plan is not None else () + + +def website_actions(website): + if website.finished_at is None or website.retired_at is not None: + return () + if not website.activated: + return (Operation.ACTIVATE, Operation.RETIRE) + if website.suspended: + return (Operation.RESUME, Operation.RETIRE) + actions = (Operation.PHP, Operation.SUSPEND) + if settings.LOCAL_WEB_HTTPS and not website.https_enabled: + actions += (Operation.HTTPS,) + return actions + + +def check_actor(account, actor): + if is_tenant(actor) and not manages_account(actor, account): + raise PermissionDenied + + +def check_version(account, version): + try: + validate_php_version(version) + except ValueError as error: + raise ValidationError({"php_version": str(error)}) from error + allowed = allowed_versions(account) + if allowed and version not in allowed: + raise ValidationError( + {"php_version": "This PHP series is outside the hosting plan."} + ) + + +@transaction.atomic +def create_website(account_id, domain, version, actor): + account = lock_hosting_account(account_id, customer_id=None) + check_actor(account, actor) + require_active_services(account) + if account_websites(account).filter( + retired_at__isnull=True + ).count() + 1 >= website_limit(account): + raise ValidationError( + "This hosting account has reached its website limit." + ) + if version: + check_version(account, version) + if WebsiteDomain.objects.filter(domain=domain).exists(): + raise ValidationError({"domain": "This domain is unavailable."}) + reservation = WebsiteDomain.objects.create(account=account, domain=domain) + return IndependentWebsite.objects.create( + reservation=reservation, requested_php_version=version + ) + + +@transaction.atomic +def queue_website_operation(account_id, site_id, operation, version, actor): + account = lock_hosting_account(account_id, customer_id=None) + check_actor(account, actor) + require_active_services(account) + website = ( + account_websites(account) + .select_for_update() + .get(pk=site_id, retired_at__isnull=True) + ) + if operation not in Operation.values: + raise ValidationError("Choose a website operation.") + if website.finished_at is None: + raise ValidationError("Wait for the current website operation.") + if operation not in website_actions(website): + raise ValidationError( + "This operation is unavailable for this website." + ) + if operation == Operation.PHP or version: + check_version(account, version) + if operation == Operation.RETIRE: + if account.backup_jobs.filter(finished_at__isnull=True).exists() or ( + WebsiteRestoreJob.objects.filter( + backup__account=account, finished_at__isnull=True + ).exists() + ): + raise ValidationError("Wait for the backup or restore to finish.") + IndependentWebsite.objects.requeue( + IndependentWebsite.objects.filter(pk=website.pk), + operation=operation, + requested_php_version=( + version + if operation in (Operation.ACTIVATE, Operation.PHP) + else website.requested_php_version + ), + ) + return website + + +def apply_website_operation(website): + site = website.spec + operation = website.operation + account = website.reservation.account + try: + require_active_services(account) + except ValidationError as error: + raise ValueError(" ".join(error.messages)) from None + if operation in (Operation.ACTIVATE, Operation.PHP): + requested = website.requested_php_version + if requested: + try: + check_version(account, requested) + except ValidationError as error: + raise ValueError(" ".join(error.messages)) from None + if operation == Operation.ACTIVATE: + plan = account.hosting_plan + _, version = activate_local_site( + site, + plan.get_php_settings() if plan else PhpPoolSettings(), + (requested,) if requested else allowed_versions(account), + ) + limit = plan.website_storage_limit_mib if plan else None + if limit is not None: + set_local_site_storage_limit(site, limit) + return { + "activated": True, + "php_version": version, + "storage_limit_mib": limit, + } + if operation == Operation.PHP: + return {"php_version": update_local_php_version(site, requested)} + if operation == Operation.HTTPS: + if not settings.LOCAL_WEB_HTTPS: + raise ValueError("Enable the website HTTPS worker first.") + enable_local_https(site) + return {"https_enabled": True} + if operation in (Operation.SUSPEND, Operation.RESUME): + suspended = operation == Operation.SUSPEND + apply_on_local_node( + ServiceAccessRequest(site, suspended), + "/run/coulobre-web-apply.sock", + "web node", + "website access", + ) + return {"suspended": suspended} + if operation == Operation.RETIRE: + request = RetirementRequest(site, str(website.retirement_id)) + apply_on_local_node( + request, + "/run/coulobre-web-apply.sock", + "web node", + "website retirement", + identity=request.identity(), + ) + return {"retired_at": timezone.now()} + raise ValueError("Unknown website operation.") diff --git a/src/coulobre/hosting/migrations/0047_independent_websites.py b/src/coulobre/hosting/migrations/0047_independent_websites.py new file mode 100644 index 0000000..dfd24f0 --- /dev/null +++ b/src/coulobre/hosting/migrations/0047_independent_websites.py @@ -0,0 +1,106 @@ +# Generated by Django 5.2.19 on 2026-11-22 10:56 + +import uuid + +import django.core.validators +import django.db.models.deletion +import django.utils.timezone +from django.db import migrations, models + + +class Migration(migrations.Migration): + dependencies = [ + ("hosting", "0046_reseller_onboarding"), + ] + + operations = [ + migrations.AddField( + model_name="hostingplan", + name="website_limit", + field=models.PositiveSmallIntegerField( + default=1, + help_text=( + "Maximum independent websites, including the primary site." + ), + validators=[django.core.validators.MinValueValidator(1)], + ), + ), + migrations.AddField( + model_name="websiterestorejob", + name="site_manifest", + field=models.JSONField(blank=True, null=True), + ), + migrations.CreateModel( + name="IndependentWebsite", + 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)), + ( + "operation", + models.CharField( + choices=[ + ("activate", "Provision website"), + ("php", "Change PHP series"), + ("https", "Enable HTTPS"), + ("suspend", "Suspend website"), + ("resume", "Resume website"), + ("retire", "Retire website"), + ], + default="activate", + max_length=8, + ), + ), + ("activated", models.BooleanField(default=False)), + ("https_enabled", models.BooleanField(default=False)), + ("suspended", models.BooleanField(default=False)), + ("retired_at", models.DateTimeField(blank=True, null=True)), + ( + "requested_php_version", + models.CharField(blank=True, max_length=5), + ), + ("php_version", models.CharField(blank=True, max_length=5)), + ( + "storage_limit_mib", + models.PositiveIntegerField(blank=True, null=True), + ), + ( + "retirement_id", + models.UUIDField(default=uuid.uuid4, editable=False), + ), + ( + "reservation", + models.OneToOneField( + on_delete=django.db.models.deletion.CASCADE, + related_name="website", + to="hosting.websitedomain", + ), + ), + ], + options={ + "indexes": [ + models.Index( + fields=["operation", "finished_at", "requested_at"], + name="hosting_ind_operati_bc432b_idx", + ) + ], + }, + ), + ] diff --git a/src/coulobre/hosting/models.py b/src/coulobre/hosting/models.py index 02214f4..8e0dd0b 100644 --- a/src/coulobre/hosting/models.py +++ b/src/coulobre/hosting/models.py @@ -39,7 +39,7 @@ from coulobre.php_pool_settings import ( PhpPoolSettingsError, ) from coulobre.php_runtime import validate_php_versions -from coulobre.web_node import MAX_STORAGE_LIMIT_MIB +from coulobre.web_node import MAX_STORAGE_LIMIT_MIB, WebSite from .fields import DomainNameField @@ -262,6 +262,11 @@ def php_plan_field(option, label): class HostingPlan(models.Model): name = models.CharField(max_length=120, unique=True) description = models.CharField(max_length=240, blank=True) + website_limit = models.PositiveSmallIntegerField( + default=1, + validators=[MinValueValidator(1)], + help_text="Maximum independent websites, including the primary site.", + ) database_limit = models.PositiveIntegerField( blank=True, null=True, @@ -893,6 +898,45 @@ class WebsiteAlias(ProvisioningJob): ] +class IndependentWebsite(ProvisioningJob): + class Operation(models.TextChoices): + ACTIVATE = "activate", "Provision website" + PHP = "php", "Change PHP series" + HTTPS = "https", "Enable HTTPS" + SUSPEND = "suspend", "Suspend website" + RESUME = "resume", "Resume website" + RETIRE = "retire", "Retire website" + + reservation = models.OneToOneField( + WebsiteDomain, on_delete=models.CASCADE, related_name="website" + ) + operation = models.CharField( + max_length=8, choices=Operation, default=Operation.ACTIVATE + ) + activated = models.BooleanField(default=False) + https_enabled = models.BooleanField(default=False) + suspended = models.BooleanField(default=False) + retired_at = models.DateTimeField(null=True, blank=True) + requested_php_version = models.CharField(max_length=5, blank=True) + php_version = models.CharField(max_length=5, blank=True) + storage_limit_mib = models.PositiveIntegerField(null=True, blank=True) + retirement_id = models.UUIDField(default=uuid.uuid4, editable=False) + + class Meta: + indexes = [ + models.Index(fields=("operation", "finished_at", "requested_at")) + ] + + def __str__(self): + return self.reservation.domain + + @property + def spec(self): + return WebSite( + self.reservation.account_id, self.reservation.domain, self.pk + ) + + class SiteSFTP(ProvisioningJob): account = models.OneToOneField( HostingAccount, on_delete=models.CASCADE, related_name="sftp" @@ -947,9 +991,9 @@ class AccountBackupJob(ProvisioningJob): return expiration is None or expiration.finished_at is not None def can_restore_website(self, site): - return ( - self.archive_is_restorable - and self.manifest.get("website") == site.manifest() + return self.archive_is_restorable and ( + self.manifest.get("website") == site.manifest() + or site.manifest() in self.manifest.get("additional_websites", []) ) @@ -973,6 +1017,7 @@ class WebsiteRestoreJob(ProvisioningJob): related_name="website_restores", ) restore_id = models.UUIDField(unique=True, editable=False) + site_manifest = models.JSONField(null=True, blank=True) filename = models.CharField(max_length=MAX_RESTORE_PATH_BYTES, blank=True) replace = models.BooleanField(default=False) operator_username = models.CharField(max_length=150) diff --git a/src/coulobre/hosting/service_changes.py b/src/coulobre/hosting/service_changes.py index df98172..45ff69a 100644 --- a/src/coulobre/hosting/service_changes.py +++ b/src/coulobre/hosting/service_changes.py @@ -8,6 +8,7 @@ from coulobre.mail_node import MailboxSpec from coulobre.service_access import ServiceAccessRequest from coulobre.web_node import WebSite +from .independent_websites import account_websites, active_websites from .models import ( AccountServiceJob, ComponentRestoreJob, @@ -62,6 +63,11 @@ def current_service_jobs(account): "Resolve pending or failed website, database, and mailbox " "provisioning before suspending services." ) + websites = account_websites(account).filter(retired_at__isnull=True) + if websites.filter(Q(finished_at__isnull=True) | ~Q(problem="")).exists(): + raise ValidationError( + "Resolve pending or failed website operations first." + ) component_restores = ComponentRestoreJob.objects.filter( backup__account=account ) @@ -81,6 +87,9 @@ def current_service_jobs(account): yield Kind.WEB, domain, site.manifest() if settings.LOCAL_WEB_SFTP or hasattr(account, "sftp"): yield Kind.SFTP, domain, site.manifest() + for website in active_websites(account): + site = website.spec + yield Kind.WEB, site.domain, site.manifest() completed_restores = component_restores.filter(problem="") restored_databases = completed_restores.filter( kind=ComponentRestoreJob.Kind.DATABASE @@ -176,9 +185,16 @@ def apply_service_change(job): raise ValueError( f"The provisioning worker for {job.target} is disabled." ) - request = ServiceAccessRequest( - resource.from_manifest(job.manifest), job.change.suspended - ) + spec = resource.from_manifest(job.manifest) + suspended = job.change.suspended + if job.kind == Kind.WEB and spec.site_id is not None and not suspended: + website = ( + active_websites(job.change.account).filter(pk=spec.site_id).first() + ) + if website is None or website.spec != spec: + raise ValueError("The additional website has changed.") + suspended = website.suspended + request = ServiceAccessRequest(spec, suspended) apply_on_local_node( request, socket, job.get_kind_display(), "service access" ) diff --git a/src/coulobre/hosting/tasks.py b/src/coulobre/hosting/tasks.py index e0b115e..cad6e2f 100644 --- a/src/coulobre/hosting/tasks.py +++ b/src/coulobre/hosting/tasks.py @@ -29,10 +29,12 @@ from .account_retirement import apply_retirement_job, finalize_retirement from .backup_restores import ( RestoreKind, available_restore_resources, + available_website_restore_targets, current_restore_resources, enabled_component_restores, ) from .backup_retention import plan_backup_expirations +from .independent_websites import active_websites, apply_website_operation from .mail_dns_setup import sync_mail_dns from .mail_policies import apply_policy, mail_policy_available from .models import ( @@ -45,6 +47,7 @@ from .models import ( DatabaseProvisioning, DnsPublication, HostingMailDomain, + IndependentWebsite, MailboxProvisioning, MailRoutingPublication, MailVacationPublication, @@ -140,6 +143,12 @@ def render_web_plan(plan_id): @shared_task def dispatch_web_activations(): if settings.LOCAL_WEB_ACTIVATION: + dispatch_provisioning_jobs( + IndependentWebsite, + provision_independent_website, + WEB_ACTIVATION_QUEUE, + condition=~Q(operation=IndependentWebsite.Operation.HTTPS), + ) dispatch_provisioning_jobs( WebActivation, activate_web_plan, WEB_ACTIVATION_QUEUE ) @@ -180,6 +189,12 @@ def dispatch_site_storage_limits(): @shared_task def dispatch_web_https(): if settings.LOCAL_WEB_HTTPS: + dispatch_provisioning_jobs( + IndependentWebsite, + provision_independent_website, + WEB_HTTPS_QUEUE, + operation=IndependentWebsite.Operation.HTTPS, + ) dispatch_provisioning_jobs(WebHTTPS, enable_web_https, WEB_HTTPS_QUEUE) if settings.LOCAL_WEB_ACTIVATION: dispatch_provisioning_jobs( @@ -739,6 +754,11 @@ def apply_account_backup(job): backup = AccountBackup.from_manifest(job.manifest) if backup.website.account_id != job.account_id: raise ValueError("The backup manifest belongs to a different account.") + current_sites = {website.spec for website in active_websites(job.account)} + if set(backup.additional_websites) - current_sites: + raise ValueError( + "An additional website is no longer available for backup." + ) if backup.mailboxes is not None: if job.remote_mail: if not settings.REMOTE_ACCOUNT_BACKUP_MAIL: @@ -823,8 +843,15 @@ def restore_website(job_id): def apply_website_restore(job): account = job.backup.account - site = WebSite(account.pk, account.primary_domain) - if not job.backup.can_restore_website(site): + site = ( + WebSite.from_manifest(job.site_manifest) + if job.site_manifest is not None + else WebSite(account.pk, account.primary_domain) + ) + if ( + available_website_restore_targets(job.backup).get(site.node_key) + != site + ): raise ValueError("The backup no longer matches the current website.") restore_local_website( WebsiteRestoreRequest( @@ -922,3 +949,16 @@ def expire_sign_in_windows(): @shared_task def send_customer_password_reset(email): send_customer_reset_email(email) + + +@shared_task(acks_late=True, reject_on_worker_lost=True) +def provision_independent_website(job_id): + if settings.LOCAL_WEB_ACTIVATION: + run_provisioning_job( + IndependentWebsite.objects.select_related( + "reservation__account__hosting_plan" + ), + job_id, + apply_website_operation, + "Could not complete the request to the web node. Try again.", + ) diff --git a/src/coulobre/hosting/templates/hosting/account_backup_archive_table.html b/src/coulobre/hosting/templates/hosting/account_backup_archive_table.html index 583c0a6..767aa0a 100644 --- a/src/coulobre/hosting/templates/hosting/account_backup_archive_table.html +++ b/src/coulobre/hosting/templates/hosting/account_backup_archive_table.html @@ -15,7 +15,9 @@ Manual {% endif %} - {% if job.includes_mailboxes %}Website, databases, and mail{% else %}Website and databases{% endif %} + + {% if job.manifest.additional_websites %}Websites{% else %}Website{% endif %}{% if job.includes_mailboxes %}, databases, and mail{% else %} and databases{% endif %} + {% if job.expired_at %} Expired diff --git a/src/coulobre/hosting/templates/hosting/account_detail.html b/src/coulobre/hosting/templates/hosting/account_detail.html index a93e5fb..be0ac05 100644 --- a/src/coulobre/hosting/templates/hosting/account_detail.html +++ b/src/coulobre/hosting/templates/hosting/account_detail.html @@ -60,6 +60,7 @@