diff --git a/docs/deployment.md b/docs/deployment.md index e28b587..9dfd1e5 100644 --- a/docs/deployment.md +++ b/docs/deployment.md @@ -1781,7 +1781,13 @@ sudo restic --repository-file "$profile/repository" \ sudo /opt/coulobre/bin/coulobre-account-backup verify-offsite vault ``` -Set `COULOBRE_OFFSITE_BACKUP_DESTINATIONS='{"vault":"Off-site vault"}'` in +On an installer-managed panel, open **Server Manager → Operator Settings → +Backups** and choose **Configure** for off-site backup destinations. Enter +the destination ID, such as `vault`. Coulobre verifies the existing +repository and enables the transfer worker for the first destination. + +For manual installations or additional destinations, set +`COULOBRE_OFFSITE_BACKUP_DESTINATIONS='{"vault":"Off-site vault"}'` in `/etc/coulobre/panel.env`. This setting contains IDs and labels. Each ID maps to a directory under `/etc/coulobre/offsite` on the backup node. diff --git a/src/coulobre/hosting/installation_views.py b/src/coulobre/hosting/installation_views.py index c765752..8ec801b 100644 --- a/src/coulobre/hosting/installation_views.py +++ b/src/coulobre/hosting/installation_views.py @@ -42,6 +42,11 @@ TOOL_FEATURES = { "LOCAL_DATABASE_PROVISIONING", ), "roundcube": ("email", "ROUNDCUBE_URL", "MAILBOX_PASSWORD_CHANGES"), + "offsite": ( + "backups", + "OFFSITE_BACKUP_DESTINATIONS", + "LOCAL_ACCOUNT_BACKUPS", + ), } TOOL_SETTINGS = { setting: tool for tool, (_, setting, _) in TOOL_FEATURES.items() @@ -302,7 +307,9 @@ class FeatureConfigurationView(UserPassesTestMixin, FormView): PanelFeaturePolicy.objects.get_or_create(pk=1) PanelFeaturePolicy.objects.select_for_update().get(pk=1) previous = ( - OperatorOperation.objects.filter(action="feature-enable") + OperatorOperation.objects.filter( + action__in=("feature-enable", TOOL_SETUP_ACTION) + ) .order_by("-pk") .first() ) @@ -371,23 +378,29 @@ class FeatureConfigurationView(UserPassesTestMixin, FormView): class ManagedToolForm(forms.Form): - hostname = forms.CharField(max_length=253, label="HTTPS hostname") + endpoint = forms.CharField(max_length=253, label="HTTPS hostname") def __init__(self, *args, tool, **kwargs): super().__init__(*args, **kwargs) self.tool = tool + if tool == "offsite": + self.fields["endpoint"] = forms.CharField( + max_length=48, label="Destination ID" + ) - def clean_hostname(self): + def clean_endpoint(self): try: - spec = ToolSetupRequest(self.tool, self.cleaned_data["hostname"]) + spec = ToolSetupRequest(self.tool, self.cleaned_data["endpoint"]) except ValueError as error: raise forms.ValidationError(str(error)) from error + if self.tool == "offsite": + return spec.endpoint if ( - f"https://{spec.hostname}" == settings.PASSWORD_RESET_ORIGIN - or WebsiteDomain.objects.filter(domain=spec.hostname).exists() + f"https://{spec.endpoint}" == settings.PASSWORD_RESET_ORIGIN + or WebsiteDomain.objects.filter(domain=spec.endpoint).exists() ): raise forms.ValidationError("Use a separate, unused hostname.") - return spec.hostname + return spec.endpoint @method_decorator(never_cache, name="dispatch") @@ -420,6 +433,7 @@ class ManagedToolSetupView(UserPassesTestMixin, FormView): ) return super().get_context_data( tool_label=HOSTING_TOOLS[self.tool], + tool=self.tool, section=TOOL_FEATURES[self.tool][0], available=managed_tool_available(self.tool), pending=package_operation_pending(job), @@ -451,12 +465,12 @@ class ManagedToolSetupView(UserPassesTestMixin, FormView): None, "Wait for the current feature setup to finish." ) return self.form_invalid(form) - spec = ToolSetupRequest(self.tool, form.cleaned_data["hostname"]) + spec = ToolSetupRequest(self.tool, form.cleaned_data["endpoint"]) queue_operator_request( self.request.user, spec, retryable=True, - parameters={"hostname": spec.hostname}, + parameters={"endpoint": spec.endpoint}, ) messages.success( self.request, f"{HOSTING_TOOLS[self.tool]} setup queued." diff --git a/src/coulobre/hosting/tasks.py b/src/coulobre/hosting/tasks.py index 8d6813a..e594312 100644 --- a/src/coulobre/hosting/tasks.py +++ b/src/coulobre/hosting/tasks.py @@ -1409,7 +1409,7 @@ def run_operator_operation(job_id): raise ValueError( "The requesting operator no longer has access." ) - spec = ToolSetupRequest(job.target, job.parameters.get("hostname")) + spec = ToolSetupRequest(job.target, job.parameters.get("endpoint")) elif job.action == "http-defaults": spec = HttpDefaultsRequest(job.target, job.parameters) else: diff --git a/src/coulobre/hosting/templates/hosting/managed_tool_setup.html b/src/coulobre/hosting/templates/hosting/managed_tool_setup.html index 60e8ec5..518276a 100644 --- a/src/coulobre/hosting/templates/hosting/managed_tool_setup.html +++ b/src/coulobre/hosting/templates/hosting/managed_tool_setup.html @@ -21,7 +21,11 @@ {% endif %} {% if available %}
-

Point a dedicated hostname at this server. Coulobre uses an existing TLS certificate for the hostname or requests one through Let's Encrypt. Keep inbound HTTP available for certificate validation.

+ {% if tool == "offsite" %} +

Enter the ID of an initialized restic repository with an SFTP profile in /etc/coulobre/offsite. Coulobre checks access before making it available for scheduled backups.

+ {% else %} +

Point a dedicated hostname at this server. Coulobre uses an existing TLS certificate for the hostname or requests one through Let's Encrypt. Keep inbound HTTP available for certificate validation.

+ {% endif %}
{% csrf_token %} {{ form.as_p }} diff --git a/src/coulobre/hosting/test_feature_configuration.py b/src/coulobre/hosting/test_feature_configuration.py index d5414d3..906bdc2 100644 --- a/src/coulobre/hosting/test_feature_configuration.py +++ b/src/coulobre/hosting/test_feature_configuration.py @@ -100,7 +100,7 @@ class FeatureConfigurationTests(TestCase): ) def test_operator_can_queue_setup_for_a_dedicated_https_tool(self): setup = reverse("panel:managed_tool_setup", args=["phpmyadmin"]) - payload = {"hostname": "database-tools.example"} + payload = {"endpoint": "database-tools.example"} self.sign_in(verified=False) self.assertEqual(self.client.post(setup, payload).status_code, 403) self.sign_in() @@ -121,7 +121,7 @@ class FeatureConfigurationTests(TestCase): setup, ) self.assertContains( - self.client.post(setup, {"hostname": "panel.example"}), + self.client.post(setup, {"endpoint": "panel.example"}), "Use a separate, unused hostname.", ) with self.captureOnCommitCallbacks(execute=True): @@ -137,6 +137,35 @@ class FeatureConfigurationTests(TestCase): self.assertEqual(operation.parameters, payload) queue.assert_called_once_with(operation.pk) + def test_backup_setup_queues_only_a_named_root_owned_profile(self): + self.sign_in() + setup = reverse("panel:managed_tool_setup", args=["offsite"]) + module = "coulobre.hosting.installation_views" + with ( + patch(f"{module}.Path") as path_factory, + patch(f"{module}.PACKAGE_ASSETS") as assets, + ): + path_factory.return_value.is_socket.return_value = True + assets.is_dir.return_value = True + self.assertContains( + self.client.get( + reverse("panel:operator_settings", args=["backups"]) + ), + setup, + ) + reply = self.client.post(setup, {"endpoint": "../unexpected"}) + self.assertContains( + reply, "Choose a configured off-site backup destination." + ) + self.assertFalse(OperatorOperation.objects.exists()) + reply = self.client.post(setup, {"endpoint": "customer-backups"}) + self.assertEqual(reply.status_code, 302) + operation = OperatorOperation.objects.get() + self.assertEqual(operation.target, "offsite") + self.assertEqual( + operation.parameters, {"endpoint": "customer-backups"} + ) + @override_settings(LOCAL_WEB_ACTIVATION=True, WEB_FILE_MANAGER=False) def test_feature_setup_can_retry_after_the_broker_is_offline(self): self.sign_in() diff --git a/src/coulobre/managed_tools.py b/src/coulobre/managed_tools.py index 0982a40..c2e5b77 100644 --- a/src/coulobre/managed_tools.py +++ b/src/coulobre/managed_tools.py @@ -1,6 +1,7 @@ """Install hosting tools on dedicated HTTPS hosts.""" import hashlib +import json import os import pwd import re @@ -35,6 +36,7 @@ from .node_files import ( require_root_directory, write_new_file, ) +from .offsite_node import verify_destination from .release_updates import UpdateError from .web_node_tls import ( CERTBOT_ROOT, @@ -54,6 +56,12 @@ APT_GET = "/usr/bin/apt-get" def install_tool(request, command): try: plan = local_update.installation_plan() + if request.target == "offsite": + with installation_configuration() as config: + enable_offsite( + request.endpoint, plan["hostname"], config, command + ) + return {"enabled": True} if plan["access"] not in {"acme", "tls"}: raise ValueError( "Managed tool setup requires direct Apache HTTPS." @@ -64,7 +72,7 @@ def install_tool(request, command): panel_host = canonical_domain(plan["hostname"]) if origin != f"https://{panel_host}": raise ValueError("Set the installer-managed panel's HTTPS origin.") - if request.hostname == panel_host: + if request.endpoint == panel_host: raise ValueError("Use a hostname separate from the panel.") mail_host = check_prerequisites(request.target, plan) with installation_configuration() as config: @@ -74,6 +82,64 @@ def install_tool(request, command): return {"enabled": True} +def enable_offsite(destination, hostname, config, command): + if os.environ.get("COULOBRE_LOCAL_ACCOUNT_BACKUPS") != "1" or not active( + "coulobre-account-backup.socket" + ): + raise ValueError("Enable local account backups first.") + if not Path("/usr/bin/restic").is_file(): + raise ValueError("Install restic and initialize the repository first.") + original = read_root_file(config, mode=0o600) + if re.search( + r"^[ \t]*COULOBRE_OFFSITE_BACKUP_DESTINATIONS[ \t]*=", original, re.M + ) or original.rstrip("\n").endswith("\\"): + raise ValueError("Review the existing off-site backup configuration.") + try: + verify_destination(destination) + except FileNotFoundError: + raise ValueError( + "Prepare this destination's root-owned SFTP profile first." + ) from None + worker = "coulobre-offsite-worker" + create_service_identity("coulobre-offsite-requests", worker, command) + install_files( + ( + (PACKAGE_ASSETS / "systemd" / name, SYSTEMD / name, 0o644) + for name in ( + "coulobre-account-offsite.socket", + "coulobre-account-offsite@.service", + f"{worker}.service", + ) + ), + package_assets=True, + ) + saved = json.dumps( + {destination: destination.replace("-", " ").capitalize()} + ) + key = "COULOBRE_OFFSITE_BACKUP_DESTINATIONS" + updated = original.rstrip("\n") + f"\n{key}='{saved}'\n" + unit = f"{worker}.service" + was_active = active(unit) + command(SYSTEMCTL, "daemon-reload") + replace_configuration(config, updated, mode=0o600) + try: + command(SYSTEMCTL, "restart" if was_active else "start", unit) + if not active("coulobre-account-offsite.socket") or not active(unit): + raise ValueError("The off-site backup service did not start.") + restart_panel(command, hostname) + command(SYSTEMCTL, "enable", unit) + except (OSError, ValueError, UpdateError): + replace_configuration(config, original, mode=0o600) + if was_active: + command(SYSTEMCTL, "restart", unit) + else: + command(SYSTEMCTL, "stop", unit, "coulobre-account-offsite.socket") + restart_panel(command, hostname) + raise ValueError( + "The backup service did not enable. Review the service journal." + ) from None + + def check_prerequisites(target, plan): if target == "phpmyadmin": if ( @@ -392,7 +458,7 @@ def prepare_roundcube(origin, mail_host, private, state, user, command): def apply_tool(request, config, origin, mail_host, command): - target, hostname = request.target, request.hostname + target, hostname = request.target, request.endpoint base = f"coulobre-{target}" url = f"https://{hostname}" + ( "/phpmyadmin" if target == "phpmyadmin" else "" diff --git a/src/coulobre/tool_setup_request.py b/src/coulobre/tool_setup_request.py index 01e8298..82be9b1 100644 --- a/src/coulobre/tool_setup_request.py +++ b/src/coulobre/tool_setup_request.py @@ -2,18 +2,20 @@ from dataclasses import dataclass from ipaddress import ip_address from .domain_names import canonical_domain +from .offsite_backup import validate_destination TOOL_SETUP_ACTION = "tool-setup" HOSTING_TOOLS = { "phpmyadmin": "phpMyAdmin", "roundcube": "Roundcube", + "offsite": "Off-site backup destination", } @dataclass(frozen=True) class ToolSetupRequest: target: str - hostname: str + endpoint: str @property def action(self): @@ -29,9 +31,12 @@ class ToolSetupRequest: or self.target not in HOSTING_TOOLS ): raise ValueError("Choose a supported hosting tool.") - if not isinstance(self.hostname, str): + if self.target == "offsite": + validate_destination(self.endpoint) + return + if not isinstance(self.endpoint, str): raise ValueError("Enter a dedicated HTTPS hostname.") - hostname = canonical_domain(self.hostname) + hostname = canonical_domain(self.endpoint) try: ip_address(hostname) except ValueError: @@ -40,24 +45,24 @@ class ToolSetupRequest: raise ValueError( "Use a hostname for the tool's HTTPS certificate." ) - object.__setattr__(self, "hostname", hostname) + object.__setattr__(self, "endpoint", hostname) def manifest(self): return { "version": 1, "operation": TOOL_SETUP_ACTION, "target": self.target, - "hostname": self.hostname, + "endpoint": self.endpoint, } @classmethod def from_manifest(cls, data): if ( not isinstance(data, dict) - or set(data) != {"version", "operation", "target", "hostname"} + or set(data) != {"version", "operation", "target", "endpoint"} or type(data["version"]) is not int or data["version"] != 1 or data["operation"] != TOOL_SETUP_ACTION ): raise ValueError("Expected a hosting tool setup request.") - return cls(data["target"], data["hostname"]) + return cls(data["target"], data["endpoint"])