Merge pull request 'Restore website files from local account backups' (#35) from feature/backup-recovery into main
Coulobre Panel CI / Checks (Python 3.12) (push) Canceled after 0s
Coulobre Panel CI / Checks (Python 3.14) (push) Canceled after 0s

Reviewed-on: #35
This commit was merged in pull request #35.
This commit is contained in:
parkel committed 2026-11-21 14:44:53 +01:00
commit 893e9b34a7
25 files changed
+1036 -32

No files matched your search

+1
View File
@@ -16,3 +16,4 @@ COULOBRE_BROKER_URL=amqp://coulobre:@127.0.0.1:5672/coulobre
# COULOBRE_LOCAL_MAILBOX_PROVISIONING=1 # COULOBRE_LOCAL_MAILBOX_PROVISIONING=1
# COULOBRE_LOCAL_ACCOUNT_BACKUPS=1 # COULOBRE_LOCAL_ACCOUNT_BACKUPS=1
# COULOBRE_LOCAL_ACCOUNT_BACKUP_MAIL=1 # COULOBRE_LOCAL_ACCOUNT_BACKUP_MAIL=1
# COULOBRE_LOCAL_WEBSITE_RESTORE=1
@@ -0,0 +1,11 @@
[Unit]
Description=Coulobre local website restore socket
[Socket]
ListenStream=/run/coulobre-account-restore.sock
SocketUser=root
SocketGroup=coulobre-restore-requests
SocketMode=0660
Accept=yes
MaxConnections=4
RemoveOnStop=true
@@ -0,0 +1,22 @@
[Unit]
Description=Coulobre local website restore request
CollectMode=inactive-or-failed
[Service]
Type=exec
User=root
WorkingDirectory=/opt/coulobre
StateDirectory=coulobre/account-restores
StateDirectoryMode=0700
ReadWritePaths=-/srv/coulobre/web
UMask=0077
ExecStart=/opt/coulobre/bin/coulobre-account-backup restore-website-request
StandardInput=socket
StandardOutput=socket
StandardError=journal
RuntimeMaxSec=30min
NoNewPrivileges=true
CapabilityBoundingSet=~CAP_SYS_RESOURCE
PrivateTmp=true
ProtectHome=true
ProtectSystem=strict
@@ -0,0 +1,6 @@
[Unit]
Requires=coulobre-account-restore.socket
After=coulobre-account-restore.socket
[Service]
SupplementaryGroups=coulobre-restore-requests
+42
View File
@@ -420,6 +420,48 @@ most one missed backup per account and continues with the next future time.
Scheduled ZIPs are stored alongside manual backups and require the same Scheduled ZIPs are stored alongside manual backups and require the same
server-side retention management. server-side retention management.
#### Restore website files from the panel
Enable this feature when the website and account backup archive are on the
same server. Install the restore socket and give the backup worker access to
it.
```sh
sudo groupadd --system coulobre-restore-requests
sudo install -m 0644 deploy/systemd/coulobre-account-restore.socket \
deploy/systemd/coulobre-account-restore@.service /etc/systemd/system/
sudo install -D -m 0644 deploy/systemd/coulobre-backup-worker.service.d/restore.conf \
/etc/systemd/system/coulobre-backup-worker.service.d/restore.conf
sudo systemctl daemon-reload
```
Set `COULOBRE_LOCAL_WEBSITE_RESTORE=1` in `/etc/coulobre/panel.env`.
```sh
panel_manage migrate --noinput
sudo systemctl restart coulobre-panel coulobre-worker coulobre-backup-worker
```
Select **Restore website** on a completed backup for the current account and
domain. Operators need the backup permissions listed above and **Can add
website restore job**. A backup that includes mail also requires permission
to view mailbox requests.
For one file, enter its path relative to the document root. Make sure the
parent directory exists. Select **Replace the existing file at this path**
only if an existing site-owned file should be overwritten. Choose **Entire
website** to restore all website files to an empty document root. When
replacing a file, its old and restored copies must fit within the website's
storage quota during staging. The **Website restores** section records the
source backup, operator, and result.
Restore request records under `/var/lib/coulobre/account-restores/` prevent
an interrupted worker from applying the same restore twice. Keep these
records while corresponding jobs could still be delivered. If the panel
cannot confirm a restore, check the destination before submitting another.
Use the [account bundle commands](development.md#recover-backups-from-the-bundle)
to recover databases, mail, or components on separate servers.
#### Include mailboxes on the same server #### Include mailboxes on the same server
Complete the [Postfix and Dovecot setup](development.md#apply-a-mailbox-manifest) Complete the [Postfix and Dovecot setup](development.md#apply-a-mailbox-manifest)
+4
View File
@@ -1073,6 +1073,10 @@ sudo /opt/coulobre/bin/coulobre-account-backup pack \
### Recover backups from the bundle ### Recover backups from the bundle
On a single-server installation, operators can restore one file or the entire
website from a completed account backup. See
[restoring from the panel](deployment.md#restore-website-files-from-the-panel).
Unpack to a new directory on a root-controlled path. The command verifies the Unpack to a new directory on a root-controlled path. The command verifies the
ZIP contents and checks the identity and integrity of each compressed ZIP contents and checks the identity and integrity of each compressed
component before publishing the directory. component before publishing the directory.
+23 -7
View File
@@ -4,6 +4,7 @@ import json
import os import os
import tarfile import tarfile
import zlib import zlib
from contextlib import contextmanager
from dataclasses import dataclass from dataclasses import dataclass
from pathlib import Path from pathlib import Path
from shutil import copyfileobj from shutil import copyfileobj
@@ -121,8 +122,17 @@ def main(argv=None):
commands.add_parser( commands.add_parser(
"create-request", help="Create a local backup for the panel worker." "create-request", help="Create a local backup for the panel worker."
) )
commands.add_parser(
"restore-website-request",
help="Restore website files for the panel worker.",
)
args = parser.parse_args(argv) args = parser.parse_args(argv)
if args.command == "restore-website-request":
from .account_restore_request import serve_website_restore
return serve_website_restore()
if args.command == "create-request": if args.command == "create-request":
from .account_backup_request import serve_backup_request from .account_backup_request import serve_backup_request
@@ -201,15 +211,11 @@ def pack_backup(backup, directory, archive):
os.link(staged.name, archive) os.link(staged.name, archive)
def unpack_backup(archive, directory): @contextmanager
def open_account_bundle(archive):
archive = private_path(archive) archive = private_path(archive)
check_root_file(archive, mode=0o600) check_root_file(archive, mode=0o600)
directory = private_path(directory, new=True) with ZipFile(archive) as bundle:
with (
ZipFile(archive) as bundle,
TemporaryDirectory(dir=directory.parent) as temporary,
):
staged = Path(temporary)
entries = bundle.infolist() entries = bundle.infolist()
if any( if any(
entry.compress_type != ZIP_STORED or entry.flag_bits & 1 entry.compress_type != ZIP_STORED or entry.flag_bits & 1
@@ -226,6 +232,16 @@ def unpack_backup(archive, directory):
with bundle.open(manifests[0]) as source: with bundle.open(manifests[0]) as source:
backup = read_backup_manifest(source) backup = read_backup_manifest(source)
validate_bundle_entries(entries, backup) validate_bundle_entries(entries, backup)
yield bundle, backup
def unpack_backup(archive, directory):
directory = private_path(directory, new=True)
with (
open_account_bundle(archive) as (bundle, backup),
TemporaryDirectory(dir=directory.parent) as temporary,
):
staged = Path(temporary)
write_new_file( write_new_file(
staged / MANIFEST_NAME, manifest_text(backup), mode=0o600 staged / MANIFEST_NAME, manifest_text(backup), mode=0o600
) )
+2 -11
View File
@@ -12,7 +12,7 @@ from .account_backup import (
read_backup_manifest, read_backup_manifest,
) )
from .database_node import DEFAULT_SOCKET from .database_node import DEFAULT_SOCKET
from .node_files import check_root_file, require_root_directory from .node_files import check_root_file, locked_root_directory
from .node_requests import serve_apply_request from .node_requests import serve_apply_request
REQUEST_VERSION = 1 REQUEST_VERSION = 1
@@ -71,8 +71,6 @@ def serve_backup_request():
def create_requested_backup(request): def create_requested_backup(request):
import fcntl
if os.geteuid() != 0: if os.geteuid() != 0:
raise ValueError("Run create-request as root on the backup node.") raise ValueError("Run create-request as root on the backup node.")
if ( if (
@@ -80,15 +78,8 @@ def create_requested_backup(request):
and os.environ.get("COULOBRE_LOCAL_ACCOUNT_BACKUP_MAIL") != "1" and os.environ.get("COULOBRE_LOCAL_ACCOUNT_BACKUP_MAIL") != "1"
): ):
raise ValueError("Enable mailbox backups on the local backup node.") raise ValueError("Enable mailbox backups on the local backup node.")
require_root_directory(BACKUP_DIRECTORY) with locked_root_directory(BACKUP_DIRECTORY):
directory = os.open(
BACKUP_DIRECTORY, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW
)
try:
fcntl.flock(directory, fcntl.LOCK_EX)
ensure_requested_archive(request) ensure_requested_archive(request)
finally:
os.close(directory)
def ensure_requested_archive(request): def ensure_requested_archive(request):
+184
View File
@@ -0,0 +1,184 @@
import errno
import json
import os
from dataclasses import dataclass
from pathlib import Path
from shutil import copyfileobj
from tempfile import TemporaryDirectory
from uuid import UUID
from zipfile import BadZipFile
from .account_backup import CHUNK_BYTES, open_account_bundle
from .account_backup_request import BACKUP_TIMEOUT_SECONDS, backup_archive
from .node_files import locked_root_directory, read_root_file, write_new_file
from .node_requests import serve_apply_request
from .web_node import WebSite
REQUEST_VERSION = 1
RESTORE_DIRECTORY = Path("/var/lib/coulobre/account-restores")
RESTORE_SOCKET = "/run/coulobre-account-restore.sock"
RESTORE_TIMEOUT_SECONDS = BACKUP_TIMEOUT_SECONDS
MAX_RESTORE_PATH_BYTES = 1024
def validate_restore_path(filename):
from .web_node_backup import relative_file_parts
if not isinstance(filename, str) or not filename.isprintable():
raise ValueError("Choose a file path relative to the document root.")
parts = relative_file_parts(filename)
if len(filename.encode("utf-8")) > MAX_RESTORE_PATH_BYTES or any(
len(part.encode("utf-8")) > 255 for part in parts
):
raise ValueError("The restore path is too long.")
@dataclass(frozen=True)
class WebsiteRestoreRequest:
restore_id: UUID
backup_id: UUID
site: WebSite
filename: str | None
replace: bool
def __post_init__(self):
if type(self.replace) is not bool:
raise ValueError("Expected a boolean replacement option.")
if self.filename is not None:
validate_restore_path(self.filename)
elif self.replace:
raise ValueError("Choose a file when replacing live content.")
@classmethod
def from_manifest(cls, data):
if (
not isinstance(data, dict)
or data.keys()
!= {
"version",
"restore_id",
"backup_id",
"site",
"filename",
"replace",
}
or type(data["version"]) is not int
or data["version"] != REQUEST_VERSION
):
raise ValueError("Expected a local website restore request.")
return cls(
parse_uuid(data["restore_id"]),
parse_uuid(data["backup_id"]),
WebSite.from_manifest(data["site"]),
data["filename"],
data["replace"],
)
def manifest(self):
return {
"version": REQUEST_VERSION,
"restore_id": str(self.restore_id),
"backup_id": str(self.backup_id),
"site": self.site.manifest(),
"filename": self.filename,
"replace": self.replace,
}
def parse_uuid(value):
if isinstance(value, str):
try:
identifier = UUID(value)
except ValueError:
pass
else:
if str(identifier) == value:
return identifier
raise ValueError("Expected a canonical restore or backup ID.")
def serve_website_restore():
return serve_apply_request(
REQUEST_VERSION,
WebsiteRestoreRequest.from_manifest,
restore_requested_website,
limit=16 * 1024,
)
def restore_requested_website(request):
if os.geteuid() != 0:
raise ValueError(
"Run restore-website-request as root on the backup node."
)
with locked_root_directory(RESTORE_DIRECTORY) as directory:
claim = RESTORE_DIRECTORY / f"{request.restore_id}.json"
result = claim.with_suffix(".result")
manifest = json.dumps(request.manifest())
try:
write_new_file(claim, manifest, mode=0o600)
except FileExistsError:
if read_root_file(claim, mode=0o600) != manifest:
raise ValueError(
"This restore ID belongs to a different request."
) from None
if not result.exists():
raise ValueError(
"The previous restore was interrupted. "
"Check the destination before requesting another restore."
) from None
problem = json.loads(read_root_file(result, mode=0o600))
else:
# Persist the claim before writing website files.
os.fsync(directory)
problem = None
try:
restore_website_from_bundle(request)
except (OSError, ValueError) as error:
problem = str(error)
write_new_file(result, json.dumps(problem), mode=0o600)
os.fsync(directory)
if problem is not None:
raise ValueError(problem)
def restore_website_from_bundle(request):
from .web_node_backup import restore_native_website
archive = backup_archive(request.site.account_id, request.backup_id)
try:
with (
open_account_bundle(archive) as (bundle, backup),
TemporaryDirectory(dir=RESTORE_DIRECTORY) as temporary,
):
if backup.website != request.site:
raise ValueError("This backup is for a different website.")
staged = Path(temporary) / "website.tar.gz"
with (
bundle.open(staged.name) as source,
staged.open("xb") as target,
):
os.fchmod(target.fileno(), 0o600)
copyfileobj(source, target, length=CHUNK_BYTES)
restore_native_website(
request.site,
staged,
filename=request.filename,
replace=request.replace,
)
except FileNotFoundError as error:
if error.filename == str(archive):
raise ValueError(
"The selected backup archive is no longer on disk."
) from None
raise
except OSError as error:
if error.errno == errno.EDQUOT:
raise ValueError(
"The restore exceeded a filesystem storage quota."
) from None
raise
except BadZipFile:
raise ValueError(
"The selected account backup ZIP is unreadable."
) from None
@@ -1,4 +1,12 @@
from uuid import uuid4
from django import forms from django import forms
from django.core.exceptions import ValidationError
from coulobre.account_restore_request import (
MAX_RESTORE_PATH_BYTES,
validate_restore_path,
)
from .models import AccountBackupSchedule from .models import AccountBackupSchedule
@@ -58,3 +66,48 @@ class AccountBackupScheduleForm(forms.Form):
"or pause the schedule.", "or pause the schedule.",
) )
return cleaned return cleaned
class WebsiteRestoreForm(forms.Form):
restore_id = forms.UUIDField(initial=uuid4, widget=forms.HiddenInput)
scope = forms.ChoiceField(
choices=(("file", "One file"), ("website", "Entire website")),
initial="file",
widget=forms.RadioSelect,
)
filename = forms.CharField(
label="File path",
max_length=MAX_RESTORE_PATH_BYTES,
required=False,
strip=False,
help_text="Use a path relative to the document root.",
)
replace = forms.BooleanField(
label="Replace the existing file at this path", required=False
)
def clean_filename(self):
filename = self.cleaned_data["filename"]
if filename:
try:
validate_restore_path(filename)
except ValueError as error:
raise ValidationError(str(error)) from error
return filename
def clean(self):
cleaned = super().clean()
if cleaned.get("scope") == "file" and cleaned.get("filename") == "":
self.add_error(
"filename", "Enter the path of the file to restore."
)
if cleaned.get("scope") == "website":
if cleaned.get("filename"):
self.add_error(
"filename", "Clear the path to restore the entire website."
)
if cleaned.get("replace"):
self.add_error(
"replace", "Replacement is only available for one file."
)
return cleaned
+41 -2
View File
@@ -1,13 +1,18 @@
from datetime import UTC, datetime, timedelta from datetime import UTC, datetime, timedelta
from django.core.exceptions import PermissionDenied from django.core.exceptions import PermissionDenied, ValidationError
from django.db import transaction from django.db import transaction
from django.utils import timezone from django.utils import timezone
from coulobre.account_backup import AccountBackup from coulobre.account_backup import AccountBackup
from coulobre.web_node import WebSite from coulobre.web_node import WebSite
from .models import AccountBackupSchedule, HostingAccount, HostingMailbox from .models import (
AccountBackupSchedule,
HostingAccount,
HostingMailbox,
WebsiteRestoreJob,
)
from .resource_requests import lock_hosting_account from .resource_requests import lock_hosting_account
@@ -110,3 +115,37 @@ def _queue_scheduled_backup(account_id, now):
) )
schedule.next_run_at = _next_backup_run(schedule, now) schedule.next_run_at = _next_backup_run(schedule, now)
schedule.save(update_fields=["next_run_at"]) schedule.save(update_fields=["next_run_at"])
@transaction.atomic
def queue_website_restore(
backup, *, restore_id, filename, replace, operator_username
):
account = lock_hosting_account(backup.account_id, customer_id=None)
if not backup.can_restore_website(
WebSite(account.pk, account.primary_domain)
):
raise ValidationError(
"Choose a completed backup of the current website."
)
jobs = WebsiteRestoreJob.objects
details = {
"backup_id": backup.pk,
"filename": filename,
"replace": replace,
"operator_username": operator_username,
}
job = jobs.filter(restore_id=restore_id).first()
if job is None:
if jobs.filter(
backup__account=account, finished_at__isnull=True
).exists():
raise ValidationError(
"Wait for the current website restore to finish."
)
job, _ = jobs.get_or_create(restore_id=restore_id, defaults=details)
if any(getattr(job, field) != value for field, value in details.items()):
raise ValidationError(
"Reopen the restore form to submit a new request."
)
@@ -0,0 +1,59 @@
# Generated by Django 5.2.19 on 2026-11-21 13:36
import django.db.models.deletion
import django.utils.timezone
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("hosting", "0025_account_backup_schedules"),
]
operations = [
migrations.CreateModel(
name="WebsiteRestoreJob",
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)),
("restore_id", models.UUIDField(editable=False, unique=True)),
("filename", models.CharField(blank=True, max_length=1024)),
("replace", models.BooleanField(default=False)),
("operator_username", models.CharField(max_length=150)),
(
"backup",
models.ForeignKey(
on_delete=django.db.models.deletion.CASCADE,
related_name="website_restores",
to="hosting.accountbackupjob",
),
),
],
options={
"indexes": [
models.Index(
fields=["finished_at", "requested_at"],
name="hosting_web_finishe_a9b362_idx",
)
],
},
),
]
+22
View File
@@ -11,6 +11,7 @@ from django.urls import reverse
from django.utils import timezone from django.utils import timezone
from coulobre.account_backup_request import backup_archive from coulobre.account_backup_request import backup_archive
from coulobre.account_restore_request import MAX_RESTORE_PATH_BYTES
from coulobre.database_node import ( from coulobre.database_node import (
DATABASE_SUFFIX_PATTERN, DATABASE_SUFFIX_PATTERN,
INVALID_SUFFIX, INVALID_SUFFIX,
@@ -458,6 +459,27 @@ class AccountBackupJob(ProvisioningJob):
def includes_mailboxes(self): def includes_mailboxes(self):
return "mailboxes" in self.manifest return "mailboxes" in self.manifest
def can_restore_website(self, site):
return (
self.state == "configured"
and self.manifest.get("website") == site.manifest()
)
class WebsiteRestoreJob(ProvisioningJob):
backup = models.ForeignKey(
AccountBackupJob,
on_delete=models.CASCADE,
related_name="website_restores",
)
restore_id = models.UUIDField(unique=True, editable=False)
filename = models.CharField(max_length=MAX_RESTORE_PATH_BYTES, blank=True)
replace = models.BooleanField(default=False)
operator_username = models.CharField(max_length=150)
class Meta:
indexes = [models.Index(fields=("finished_at", "requested_at"))]
class AccountBackupSchedule(models.Model): class AccountBackupSchedule(models.Model):
class Frequency(models.TextChoices): class Frequency(models.TextChoices):
+14
View File
@@ -5,6 +5,10 @@ from coulobre.account_backup_request import (
BACKUP_SOCKET, BACKUP_SOCKET,
BACKUP_TIMEOUT_SECONDS, BACKUP_TIMEOUT_SECONDS,
) )
from coulobre.account_restore_request import (
RESTORE_SOCKET,
RESTORE_TIMEOUT_SECONDS,
)
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,
@@ -106,6 +110,16 @@ def create_local_account_backup(request):
) )
def restore_local_website(request):
apply_on_local_node(
request,
RESTORE_SOCKET,
"backup node",
"website restore",
timeout=RESTORE_TIMEOUT_SECONDS + 15,
)
def encode_manifest(manifest): def encode_manifest(manifest):
return json.dumps(manifest).encode("utf-8") return json.dumps(manifest).encode("utf-8")
+44
View File
@@ -10,6 +10,10 @@ from coulobre.account_backup_request import (
BACKUP_TIMEOUT_SECONDS, BACKUP_TIMEOUT_SECONDS,
AccountBackupRequest, AccountBackupRequest,
) )
from coulobre.account_restore_request import (
RESTORE_TIMEOUT_SECONDS,
WebsiteRestoreRequest,
)
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 WebSite
@@ -26,6 +30,7 @@ from .models import (
WebActivation, WebActivation,
WebHTTPS, WebHTTPS,
WebProvisioningPlan, WebProvisioningPlan,
WebsiteRestoreJob,
) )
from .node_client import ( from .node_client import (
activate_local_site, activate_local_site,
@@ -35,6 +40,7 @@ from .node_client import (
provision_local_database, provision_local_database,
provision_local_mailbox, provision_local_mailbox,
publish_local_zone, publish_local_zone,
restore_local_website,
set_local_site_storage_limit, set_local_site_storage_limit,
update_local_mailbox_quota, update_local_mailbox_quota,
update_local_sftp, update_local_sftp,
@@ -43,6 +49,7 @@ from .sftp import site_is_active
REDISPATCH_AFTER = timedelta(minutes=5) REDISPATCH_AFTER = timedelta(minutes=5)
ACCOUNT_BACKUP_LEASE = timedelta(seconds=BACKUP_TIMEOUT_SECONDS + 60) ACCOUNT_BACKUP_LEASE = timedelta(seconds=BACKUP_TIMEOUT_SECONDS + 60)
WEBSITE_RESTORE_LEASE = timedelta(seconds=RESTORE_TIMEOUT_SECONDS + 60)
ACCOUNT_BACKUP_QUEUE = "coulobre-account-backups" ACCOUNT_BACKUP_QUEUE = "coulobre-account-backups"
WEB_ACTIVATION_QUEUE = "coulobre-web-activation" WEB_ACTIVATION_QUEUE = "coulobre-web-activation"
WEB_HTTPS_QUEUE = "coulobre-web-https" WEB_HTTPS_QUEUE = "coulobre-web-https"
@@ -160,6 +167,14 @@ def dispatch_account_backups():
lease=ACCOUNT_BACKUP_LEASE, lease=ACCOUNT_BACKUP_LEASE,
) )
if settings.LOCAL_WEBSITE_RESTORE:
dispatch_provisioning_jobs(
WebsiteRestoreJob,
restore_website,
ACCOUNT_BACKUP_QUEUE,
lease=WEBSITE_RESTORE_LEASE,
)
def dispatch_provisioning_jobs(model, task, queue, *, lease=REDISPATCH_AFTER): def dispatch_provisioning_jobs(model, task, queue, *, lease=REDISPATCH_AFTER):
now = timezone.now() now = timezone.now()
@@ -371,6 +386,35 @@ def apply_account_backup(job):
create_local_account_backup(AccountBackupRequest(job.backup_id, backup)) create_local_account_backup(AccountBackupRequest(job.backup_id, backup))
@shared_task(acks_late=True, reject_on_worker_lost=True)
def restore_website(job_id):
if settings.LOCAL_ACCOUNT_BACKUPS and settings.LOCAL_WEBSITE_RESTORE:
run_provisioning_job(
WebsiteRestoreJob.objects.select_related("backup__account"),
job_id,
apply_website_restore,
"Could not confirm the restore on the local backup node. "
"Check the destination before requesting another restore.",
lease=WEBSITE_RESTORE_LEASE,
)
def apply_website_restore(job):
account = job.backup.account
site = WebSite(account.pk, account.primary_domain)
if not job.backup.can_restore_website(site):
raise ValueError("The backup no longer matches the current website.")
restore_local_website(
WebsiteRestoreRequest(
job.restore_id,
job.backup.backup_id,
site,
job.filename or None,
job.replace,
)
)
def run_provisioning_job( def run_provisioning_job(
jobs, job_id, apply, connection_problem, *, lease=REDISPATCH_AFTER jobs, job_id, apply, connection_problem, *, lease=REDISPATCH_AFTER
): ):
@@ -62,6 +62,9 @@
<td> <td>
{% if job.state == "configured" %} {% if job.state == "configured" %}
<code>{{ job.archive }}</code> <code>{{ job.archive }}</code>
{% if job.pk in website_restore_sources %}
<div><a href="{% url 'panel:website_restore' account.pk job.pk %}">Restore website</a></div>
{% endif %}
{% elif job.problem %} {% elif job.problem %}
{{ job.problem }} {{ job.problem }}
{% endif %} {% endif %}
@@ -75,3 +78,7 @@
<p class="empty">No backups requested.</p> <p class="empty">No backups requested.</p>
{% endif %} {% endif %}
</section> </section>
{% if website_restore_jobs %}
{% include "hosting/website_restore_history.html" %}
{% endif %}
@@ -0,0 +1,22 @@
{% extends "hosting/base.html" %}
{% block title %}Restore website · Coulobre Panel{% endblock %}
{% block content %}
<a class="back-link" href="{{ account.get_absolute_url }}#backups-heading">← {{ account.name }}</a>
<header class="page-heading">
<div>
<h1>Restore website</h1>
<p class="heading-meta">{{ account.primary_domain }} · Backup requested {{ backup.requested_at|date:"j M Y, H:i" }} UTC</p>
</div>
</header>
<section class="surface editor-surface">
<p>Restoring the entire website requires an empty document root. For a single file, its parent directory must already exist.</p>
<form method="post" class="editor">
{% csrf_token %}
{{ form.as_div }}
<div class="form-actions">
<button class="button primary" type="submit">Queue website restore</button>
<a class="button secondary" href="{{ account.get_absolute_url }}#backups-heading">Cancel</a>
</div>
</form>
</section>
{% endblock %}
@@ -0,0 +1,37 @@
<section class="surface" aria-labelledby="website-restores-heading">
<header class="section-heading">
<h2 id="website-restores-heading">Website restores</h2>
</header>
<div class="table-scroll">
<table>
<thead>
<tr><th scope="col">Requested</th><th scope="col">Operator</th><th scope="col">Backup requested</th><th scope="col">Restore target</th><th scope="col">Status</th></tr>
</thead>
<tbody>
{% for restore in website_restore_jobs %}
<tr>
<td>{{ restore.requested_at|date:"j M Y, H:i" }} UTC</td>
<td>{{ restore.operator_username }}</td>
<td>{{ restore.backup.requested_at|date:"j M Y, H:i" }} UTC</td>
<td>
{% if restore.filename %}
<code>{{ restore.filename }}</code>
{% if restore.replace %}(replacement allowed){% endif %}
{% else %}
Entire website
{% endif %}
</td>
<td>
{% if restore.state == "configured" %}
Restored
{% else %}
{{ restore.state|capfirst }}
{% endif %}
{% if restore.problem %}<div>{{ restore.problem }}</div>{% endif %}
</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
</section>
@@ -264,7 +264,7 @@ class AccountBackupRequestTests(SimpleTestCase):
) )
) )
self.enterContext( self.enterContext(
patch.object(account_backup_request, "require_root_directory") patch.object(account_backup_request, "locked_root_directory")
) )
self.enterContext( self.enterContext(
patch.object(account_backup_request, "check_root_file") patch.object(account_backup_request, "check_root_file")
@@ -0,0 +1,330 @@
import json
from pathlib import Path
from tempfile import TemporaryDirectory
from unittest.mock import patch
from uuid import uuid4
from zipfile import ZipFile
from django.contrib.auth import get_user_model
from django.contrib.auth.models import Permission
from django.test import SimpleTestCase, TestCase, override_settings
from django.urls import reverse
from django.utils import timezone
from coulobre import (
account_backup,
account_backup_request,
account_restore_request,
)
from coulobre.account_backup import AccountBackup
from coulobre.account_restore_request import WebsiteRestoreRequest
from coulobre.database_node import DatabaseSpec
from coulobre.web_node import WebSite
from .models import (
AccountBackupJob,
Customer,
HostingAccount,
WebsiteRestoreJob,
)
from .tasks import (
ACCOUNT_BACKUP_QUEUE,
dispatch_account_backups,
restore_website,
)
@override_settings(LOCAL_ACCOUNT_BACKUPS=True, LOCAL_WEBSITE_RESTORE=True)
class PanelWebsiteRestoreTests(TestCase):
@classmethod
def setUpTestData(cls):
users = get_user_model().objects
cls.operator = users.create_superuser("operator")
cls.customer = Customer.objects.create(user=users.create_user("owner"))
cls.account = HostingAccount.objects.create(
name="Example account",
primary_domain="example.net",
customer=cls.customer,
)
cls.site = WebSite(cls.account.pk, cls.account.primary_domain)
cls.backup = AccountBackupJob.objects.create(
account=cls.account,
manifest=AccountBackup(cls.site, ()).manifest(),
finished_at=timezone.now(),
)
def setUp(self):
self.client.force_login(self.operator)
self.url = reverse(
"panel:website_restore", args=[self.account.pk, self.backup.pk]
)
self.restore_id = uuid4()
def submit(self, **fields):
data = {
"restore_id": str(self.restore_id),
"scope": "file",
"filename": "assets/site.css",
}
return self.client.post(self.url, data | fields)
def test_backup_links_to_the_restore_form_and_worker_reports_success(self):
page = self.client.get(self.account.get_absolute_url())
self.assertContains(page, "Restore website")
self.assertContains(self.client.get(self.url), 'name="restore_id"')
self.assertRedirects(
self.submit(replace="on"), self.account.get_absolute_url()
)
job = WebsiteRestoreJob.objects.get()
self.assertEqual(job.operator_username, "operator")
self.assertEqual(job.backup, self.backup)
self.assertTrue(job.replace)
with patch.object(restore_website, "apply_async") as publish:
dispatch_account_backups()
publish.assert_called_once_with(
args=[job.pk], queue=ACCOUNT_BACKUP_QUEUE, retry=False
)
with patch("coulobre.hosting.tasks.restore_local_website") as restore:
restore_website(job.pk)
restore_website(job.pk)
restore.assert_called_once_with(
WebsiteRestoreRequest(
self.restore_id,
self.backup.backup_id,
self.site,
"assets/site.css",
True,
)
)
self.assertRedirects(
self.submit(replace="on"), self.account.get_absolute_url()
)
self.assertEqual(WebsiteRestoreJob.objects.count(), 1)
page = self.client.get(self.account.get_absolute_url())
self.assertContains(page, "Website restores")
self.assertContains(page, "Restored")
self.assertContains(page, "assets/site.css")
def test_blank_file_and_invalid_scopes_never_queue_a_whole_site_restore(
self,
):
for fields in (
{"filename": ""},
{"filename": "/index.php"},
{"filename": "assets/../index.php"},
{"scope": "website"},
{"scope": "website", "filename": "", "replace": "on"},
):
with self.subTest(fields=fields):
self.assertEqual(self.submit(**fields).status_code, 200)
self.assertFalse(WebsiteRestoreJob.objects.exists())
def test_full_website_restore_and_stale_form_inputs(self):
self.assertEqual(
self.submit(scope="website", filename="").status_code, 302
)
response = self.submit()
self.assertContains(response, "Reopen the restore form")
response = self.submit(restore_id=str(uuid4()))
self.assertContains(response, "Wait for the current website restore")
job = WebsiteRestoreJob.objects.get()
with patch("coulobre.hosting.tasks.restore_local_website") as restore:
restore_website(job.pk)
self.assertIsNone(restore.call_args.args[0].filename)
self.assertFalse(restore.call_args.args[0].replace)
def test_restore_requires_a_completed_backup_for_the_current_site(
self,
):
other = HostingAccount.objects.create(
name="Other", primary_domain="other.net"
)
wrong_url = reverse(
"panel:website_restore", args=[other.pk, self.backup.pk]
)
self.assertEqual(self.client.get(wrong_url).status_code, 404)
AccountBackupJob.objects.filter(pk=self.backup.pk).update(
finished_at=None
)
self.assertEqual(self.submit().status_code, 404)
AccountBackupJob.objects.filter(pk=self.backup.pk).update(
finished_at=timezone.now()
)
self.assertEqual(self.submit().status_code, 302)
HostingAccount.objects.filter(pk=self.account.pk).update(
primary_domain="new.net"
)
self.assertEqual(self.submit().status_code, 404)
job = WebsiteRestoreJob.objects.get()
with patch("coulobre.hosting.tasks.restore_local_website") as restore:
restore_website(job.pk)
restore.assert_not_called()
job.refresh_from_db()
self.assertEqual(job.state, "failed")
self.assertIn("no longer matches", job.problem)
@override_settings(LOCAL_WEBSITE_RESTORE=False)
def test_setting_disables_submission_and_dispatch(self):
self.assertEqual(self.submit().status_code, 404)
self.assertNotContains(
self.client.get(self.account.get_absolute_url()), "Restore website"
)
with patch.object(restore_website, "apply_async") as publish:
dispatch_account_backups()
publish.assert_not_called()
def test_permissions_cover_the_backup_source_and_restore_history(self):
AccountBackupJob.objects.filter(pk=self.backup.pk).update(
manifest=AccountBackup(self.site, (), ()).manifest()
)
self.assertEqual(self.submit().status_code, 302)
operator = get_user_model().objects.create_user("limited")
perms = Permission.objects.filter(content_type__app_label="hosting")
operator.user_permissions.add(
*perms.filter(
codename__in=(
"view_hostingaccount",
"view_webprovisioningplan",
"view_hostingdatabase",
"add_accountbackupjob",
)
)
)
self.client.force_login(operator)
self.assertEqual(self.submit().status_code, 403)
operator.user_permissions.add(
perms.get(codename="add_websiterestorejob")
)
self.assertEqual(self.submit().status_code, 404)
self.assertNotContains(
self.client.get(self.account.get_absolute_url()),
"Website restores",
)
operator.user_permissions.add(
perms.get(codename="view_hostingmailbox")
)
self.assertEqual(self.client.get(self.url).status_code, 200)
self.assertContains(
self.client.get(self.account.get_absolute_url()),
"Website restores",
)
def test_read_only_customer_preview_cannot_queue_a_restore(self):
action = reverse("panel:impersonation_start", args=[self.customer.pk])
self.assertEqual(self.client.post(action).status_code, 302)
self.assertEqual(self.client.get(self.url).status_code, 403)
self.assertEqual(self.submit().status_code, 403)
self.assertFalse(WebsiteRestoreJob.objects.exists())
class WebsiteRestoreRequestTests(SimpleTestCase):
def setUp(self):
directory = Path(self.enterContext(TemporaryDirectory()))
self.request = WebsiteRestoreRequest(
uuid4(),
uuid4(),
WebSite(12, "example.net"),
"assets/site.css",
True,
)
self.directory = directory
self.enterContext(
patch.object(
account_restore_request, "RESTORE_DIRECTORY", directory
)
)
self.enterContext(
patch.object(account_backup_request, "BACKUP_DIRECTORY", directory)
)
self.archive = account_backup_request.backup_archive(
self.request.site.account_id, self.request.backup_id
)
self.enterContext(patch("coulobre.node_files.require_root_directory"))
self.enterContext(
patch.object(account_restore_request.os, "geteuid", return_value=0)
)
self.enterContext(
patch.object(account_backup, "require_root_directory")
)
self.enterContext(patch.object(account_backup, "check_root_file"))
self.enterContext(
patch.object(
account_restore_request,
"read_root_file",
side_effect=lambda path, **kwargs: path.read_text(
encoding="utf-8"
),
)
)
self.restore = self.enterContext(
patch(
"coulobre.web_node_backup.restore_native_website",
side_effect=self.check_stage,
)
)
def check_stage(self, site, archive, *, filename, replace):
self.assertEqual(site, self.request.site)
self.assertEqual(filename, self.request.filename)
self.assertTrue(replace)
self.assertEqual(archive.read_bytes(), b"native website")
self.assertEqual(list(archive.parent.iterdir()), [archive])
def build_archive(self, site):
database = DatabaseSpec(site.account_id, "cms")
with ZipFile(self.archive, "w") as bundle:
bundle.writestr(
"manifest.json",
json.dumps(AccountBackup(site, (database,)).manifest()),
)
bundle.writestr("website.tar.gz", b"native website")
bundle.writestr("database-cms.sql.gz", b"sql")
def test_requests_reject_raw_archive_paths_and_unsafe_filenames(self):
payload = self.request.manifest()
for fields in (
{"archive": "/tmp/local.zip"},
{"restore_id": self.request.restore_id.hex},
{"filename": "/index.php"},
{"filename": "assets//index.php"},
{"filename": None},
{"filename": "a" * 256},
{"replace": 1},
):
with self.subTest(fields=fields), self.assertRaises(ValueError):
WebsiteRestoreRequest.from_manifest(payload | fields)
def test_successful_replay_does_not_restore_again(self):
self.build_archive(self.request.site)
account_restore_request.restore_requested_website(self.request)
self.archive.unlink()
account_restore_request.restore_requested_website(self.request)
self.restore.assert_called_once()
different = WebsiteRestoreRequest.from_manifest(
self.request.manifest() | {"filename": "other.php"}
)
with self.assertRaisesMessage(ValueError, "different request"):
account_restore_request.restore_requested_website(different)
def test_interrupted_request_is_never_replayed_against_live_files(self):
self.build_archive(self.request.site)
with (
patch.object(
account_restore_request,
"restore_website_from_bundle",
side_effect=SystemExit,
),
self.assertRaises(SystemExit),
):
account_restore_request.restore_requested_website(self.request)
with self.assertRaisesMessage(ValueError, "Check the destination"):
account_restore_request.restore_requested_website(self.request)
self.restore.assert_not_called()
def test_an_archive_for_another_site_is_rejected_before_restoring(self):
self.build_archive(WebSite(13, "example.net"))
for _ in range(2):
with self.assertRaisesMessage(ValueError, "different website"):
account_restore_request.restore_requested_website(self.request)
self.restore.assert_not_called()
+5
View File
@@ -45,6 +45,11 @@ urlpatterns = [
views.EditAccountBackupSchedule.as_view(), views.EditAccountBackupSchedule.as_view(),
name="account_backup_schedule", name="account_backup_schedule",
), ),
path(
"accounts/<int:pk>/backups/<int:backup_pk>/restore/",
views.RequestWebsiteRestore.as_view(),
name="website_restore",
),
path( path(
"accounts/<int:pk>/sftp/", "accounts/<int:pk>/sftp/",
views.SiteSFTPKeys.as_view(), views.SiteSFTPKeys.as_view(),
+80 -1
View File
@@ -29,6 +29,7 @@ from django.views.generic.detail import SingleObjectMixin
from coulobre.dns_node import MAX_SOA_SERIAL from coulobre.dns_node import MAX_SOA_SERIAL
from coulobre.mail_node import INVALID_LOCAL_PART from coulobre.mail_node import INVALID_LOCAL_PART
from coulobre.sftp_keys import public_key_fingerprint from coulobre.sftp_keys import public_key_fingerprint
from coulobre.web_node import WebSite
from .access import ( from .access import (
OperatorOnlyMixin, OperatorOnlyMixin,
@@ -37,10 +38,15 @@ from .access import (
is_tenant, is_tenant,
reseller_for_user, reseller_for_user,
) )
from .account_backup_forms import SCHEDULE_FIELDS, AccountBackupScheduleForm from .account_backup_forms import (
SCHEDULE_FIELDS,
AccountBackupScheduleForm,
WebsiteRestoreForm,
)
from .account_backups import ( from .account_backups import (
account_backup_manifest, account_backup_manifest,
queue_account_backup, queue_account_backup,
queue_website_restore,
save_backup_schedule, save_backup_schedule,
) )
from .dns_forms import DnsZoneEditForm, DnsZoneForm, format_txt_record from .dns_forms import DnsZoneEditForm, DnsZoneForm, format_txt_record
@@ -52,6 +58,7 @@ from .impersonation import (
start_impersonation, start_impersonation,
) )
from .models import ( from .models import (
AccountBackupJob,
AccountBackupSchedule, AccountBackupSchedule,
Customer, Customer,
DatabaseProvisioning, DatabaseProvisioning,
@@ -64,6 +71,7 @@ from .models import (
WebActivation, WebActivation,
WebHTTPS, WebHTTPS,
WebProvisioningPlan, WebProvisioningPlan,
WebsiteRestoreJob,
) )
from .reseller_accounts import create_reseller_account from .reseller_accounts import create_reseller_account
from .resource_requests import ( from .resource_requests import (
@@ -107,6 +115,7 @@ MANAGE_BACKUP_SCHEDULE = (
*MANAGE_ACCOUNT_BACKUPS, *MANAGE_ACCOUNT_BACKUPS,
"hosting.change_accountbackupschedule", "hosting.change_accountbackupschedule",
) )
RESTORE_WEBSITE = (*MANAGE_ACCOUNT_BACKUPS, "hosting.add_websiterestorejob")
ACTIVATE_WEB = (VIEW_ACCOUNTS, VIEW_PLANS, "hosting.add_webactivation") ACTIVATE_WEB = (VIEW_ACCOUNTS, VIEW_PLANS, "hosting.add_webactivation")
ENABLE_WEB_HTTPS = (VIEW_ACCOUNTS, VIEW_PLANS, "hosting.add_webhttps") ENABLE_WEB_HTTPS = (VIEW_ACCOUNTS, VIEW_PLANS, "hosting.add_webhttps")
PROVISION_DATABASE = ( PROVISION_DATABASE = (
@@ -306,6 +315,24 @@ class AccountDetail(TenantScopeMixin, PermissionRequiredMixin, DetailView):
else [job for job in jobs if not job.includes_mailboxes] else [job for job in jobs if not job.includes_mailboxes]
) )
context["account_backup_jobs"] = visible_jobs context["account_backup_jobs"] = visible_jobs
if user.has_perm("hosting.add_websiterestorejob"):
if settings.LOCAL_WEBSITE_RESTORE:
site = WebSite(self.object.pk, self.object.primary_domain)
context["website_restore_sources"] = {
job.pk
for job in visible_jobs
if job.can_restore_website(site)
}
restores = WebsiteRestoreJob.objects.filter(
backup__account=self.object
).select_related("backup")
if not can_view_mailboxes:
restores = restores.exclude(
backup__manifest__has_key="mailboxes"
)
context["website_restore_jobs"] = restores.order_by(
"-requested_at", "-pk"
)[:10]
pending = next( pending = next(
(job for job in jobs if job.finished_at is None), None (job for job in jobs if job.finished_at is None), None
) )
@@ -490,6 +517,58 @@ class RequestAccountBackup(OperatorOnlyMixin, PermissionRequiredMixin, View):
return redirect("panel:account", pk=pk) return redirect("panel:account", pk=pk)
class RequestWebsiteRestore(
OperatorOnlyMixin, PermissionRequiredMixin, FormView
):
permission_required = RESTORE_WEBSITE
form_class = WebsiteRestoreForm
template_name = "hosting/website_restore.html"
def dispatch(self, request, *args, **kwargs):
if not (
settings.LOCAL_ACCOUNT_BACKUPS and settings.LOCAL_WEBSITE_RESTORE
):
raise Http404
return super().dispatch(request, *args, **kwargs)
@cached_property
def backup(self):
backup = get_object_or_404(
AccountBackupJob.objects.select_related("account"),
pk=self.kwargs["backup_pk"],
account_id=self.kwargs["pk"],
)
site = WebSite(backup.account_id, backup.account.primary_domain)
if not backup.can_restore_website(site):
raise Http404
if backup.includes_mailboxes and not self.request.user.has_perm(
VIEW_MAILBOXES
):
raise Http404
return backup
def get_context_data(self, **kwargs):
return super().get_context_data(
account=self.backup.account, backup=self.backup, **kwargs
)
def form_valid(self, form):
try:
queue_website_restore(
self.backup,
restore_id=form.cleaned_data["restore_id"],
filename=form.cleaned_data["filename"],
replace=form.cleaned_data["replace"],
operator_username=self.request.user.get_username(),
)
except HostingAccount.DoesNotExist:
raise Http404 from None
except ValidationError as error:
form.add_error(None, error)
return self.form_invalid(form)
return redirect(self.backup.account)
class EditAccountBackupSchedule( class EditAccountBackupSchedule(
OperatorOnlyMixin, PermissionRequiredMixin, FormView OperatorOnlyMixin, PermissionRequiredMixin, FormView
): ):
+14
View File
@@ -1,5 +1,6 @@
import os import os
import stat import stat
from contextlib import contextmanager
from tempfile import NamedTemporaryFile from tempfile import NamedTemporaryFile
@@ -49,3 +50,16 @@ def write_new_file(path, content, *, mode, group=None):
os.fchmod(staged.fileno(), mode) os.fchmod(staged.fileno(), mode)
os.fsync(staged.fileno()) os.fsync(staged.fileno())
os.link(staged.name, path) os.link(staged.name, path)
@contextmanager
def locked_root_directory(path):
import fcntl
require_root_directory(path)
fd = os.open(path, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW)
try:
fcntl.flock(fd, fcntl.LOCK_EX)
yield fd
finally:
os.close(fd)
+4
View File
@@ -132,6 +132,10 @@ LOCAL_ACCOUNT_BACKUPS = os.environ.get("COULOBRE_LOCAL_ACCOUNT_BACKUPS") == "1"
LOCAL_ACCOUNT_BACKUP_MAIL = ( LOCAL_ACCOUNT_BACKUP_MAIL = (
os.environ.get("COULOBRE_LOCAL_ACCOUNT_BACKUP_MAIL") == "1" os.environ.get("COULOBRE_LOCAL_ACCOUNT_BACKUP_MAIL") == "1"
) )
LOCAL_WEBSITE_RESTORE = (
LOCAL_ACCOUNT_BACKUPS
and os.environ.get("COULOBRE_LOCAL_WEBSITE_RESTORE") == "1"
)
CELERY_BEAT_SCHEDULE = { CELERY_BEAT_SCHEDULE = {
"dispatch-web-provisioning-plans": { "dispatch-web-provisioning-plans": {
"task": "coulobre.hosting.tasks.dispatch_web_plans", "task": "coulobre.hosting.tasks.dispatch_web_plans",
+8 -10
View File
@@ -3,7 +3,7 @@ import json
import os import os
import stat import stat
import tarfile import tarfile
from contextlib import contextmanager from contextlib import ExitStack, contextmanager
from io import BytesIO from io import BytesIO
from pathlib import Path from pathlib import Path
from tempfile import NamedTemporaryFile, TemporaryDirectory from tempfile import NamedTemporaryFile, TemporaryDirectory
@@ -302,13 +302,11 @@ def publish_restored_file(staged, public, selected, uid, replace):
@contextmanager @contextmanager
def open_restore_parent(fd, parts, uid): def open_restore_parent(fd, parts, uid):
if not parts: with ExitStack() as opened:
for part in parts:
fd = opened.enter_context(open_directory(part, parent=fd))
if os.fstat(fd).st_uid != uid:
raise ValueError(
"A directory in the restore path belongs to another user."
)
yield fd yield fd
return
with open_directory(parts[0], parent=fd) as child:
if os.fstat(child).st_uid != uid:
raise ValueError(
"The restore path contains a directory owned by another user."
)
with open_restore_parent(child, parts[1:], uid) as parent:
yield parent