Queue and track website restores from the hosting panel

This commit is contained in:
parkel committed 2026-11-21 14:42:38 +01:00
1 parent b9e54c9575
commit 215894aa24
13 files changed
+718 -3

No files matched your search

@@ -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>
@@ -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
): ):
+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",