diff --git a/src/coulobre/hosting/account_backup_forms.py b/src/coulobre/hosting/account_backup_forms.py index 3ef7155..6032564 100644 --- a/src/coulobre/hosting/account_backup_forms.py +++ b/src/coulobre/hosting/account_backup_forms.py @@ -3,6 +3,7 @@ from uuid import uuid4 from django import forms from django.core.exceptions import ValidationError +from coulobre.account_backup_retention import MAX_RETAINED_BACKUPS from coulobre.account_restore_request import ( MAX_RESTORE_PATH_BYTES, validate_restore_path, @@ -134,3 +135,24 @@ class ComponentRestoreForm(BackupRestoreForm): for key, target in targets.items() ), ] + + +class BackupRetentionForm(forms.Form): + count = forms.IntegerField( + label="Scheduled backups to keep", + min_value=1, + max_value=MAX_RETAINED_BACKUPS, + required=False, + help_text=( + "Leave blank to disable automatic expiration. " + "Manual and protected backups are kept separately." + ), + ) + + +class BackupProtectionForm(forms.Form): + protected = forms.TypedChoiceField( + label="Archive protection", + choices=(("1", "Protected"), ("0", "Eligible for retention")), + coerce=lambda value: value == "1", + ) diff --git a/src/coulobre/hosting/templates/hosting/account_backup_archive_table.html b/src/coulobre/hosting/templates/hosting/account_backup_archive_table.html new file mode 100644 index 0000000..583c0a6 --- /dev/null +++ b/src/coulobre/hosting/templates/hosting/account_backup_archive_table.html @@ -0,0 +1,67 @@ +{% if account_backup_jobs %} +
+ + + + + + {% for job in account_backup_jobs %} + + + + + + + + {% endfor %} + +
RequestedSourceContentsStatusArchive
{{ job.requested_at|date:"j M Y, H:i" }} UTC + {% if job.scheduled_for %} + Scheduled + {% else %} + Manual + {% endif %} + {% if job.includes_mailboxes %}Website, databases, and mail{% else %}Website and databases{% endif %} + {% if job.expired_at %} + Expired + {% elif job.state == "configured" and not job.archive_is_restorable %} + Expiration pending + {% elif job.state == "configured" %} + Ready + {% else %} + {{ job.state|capfirst }} + {% endif %} + + {% if job.expired_at %} + Removed {{ job.expired_at|date:"j M Y, H:i" }} UTC + {% elif job.state == "configured" %} + {{ job.archive }} + {% if job.archive_bytes %}
{{ job.archive_bytes|filesizeformat }}
{% endif %} + {% if job.retention_protected %}
Protected from retention
{% endif %} + {% if manage_backup_retention and job.scheduled_for %} + + {% endif %} + {% if manage_backup_retention and job.expiration.problem %} +
{{ job.expiration.problem }}
+ {% endif %} + {% if job.pk in website_restore_sources or job.pk in database_restore_sources or job.pk in mailbox_restore_sources %} +
+ {% if job.pk in website_restore_sources %} + Restore website + {% endif %} + {% if job.pk in database_restore_sources %} + Restore database + {% endif %} + {% if job.pk in mailbox_restore_sources %} + Restore mailbox + {% endif %} +
+ {% endif %} + {% elif job.problem %} + {{ job.problem }} + {% endif %} +
+
+{% elif not account_backup_pending_hidden %} +

No backups requested.

+{% endif %} diff --git a/src/coulobre/hosting/templates/hosting/account_backup_archives.html b/src/coulobre/hosting/templates/hosting/account_backup_archives.html new file mode 100644 index 0000000..b32cafc --- /dev/null +++ b/src/coulobre/hosting/templates/hosting/account_backup_archives.html @@ -0,0 +1,29 @@ +{% extends "hosting/base.html" %} +{% block title %}Backup archives · Coulobre Panel{% endblock %} +{% block content %} + ← {{ account.name }} +
+
+

Backup archives

+

{{ account.primary_domain }}

+
+ {% if manage_backup_retention %} +
+ Manage retention +
+ {% endif %} +
+
+ {% if manage_backup_retention %} +
+ {% if account.scheduled_backups_to_keep %} +

Keep {{ account.scheduled_backups_to_keep }} scheduled backup{{ account.scheduled_backups_to_keep|pluralize }}, plus manual and protected backups.

+ {% else %} +

Automatic expiration is disabled for this account.

+ {% endif %} +
+ {% endif %} + {% include "hosting/account_backup_archive_table.html" %} + {% include "hosting/pagination.html" %} +
+{% endblock %} diff --git a/src/coulobre/hosting/templates/hosting/account_backups.html b/src/coulobre/hosting/templates/hosting/account_backups.html index b6b3269..02e5f80 100644 --- a/src/coulobre/hosting/templates/hosting/account_backups.html +++ b/src/coulobre/hosting/templates/hosting/account_backups.html @@ -26,67 +26,16 @@ {% endif %} - {% if edit_account_backup_schedule %} -
+
+ Backup archives + {% if edit_account_backup_schedule %} {% if account_backup_schedule %}Edit backup schedule{% else %}Schedule backups{% endif %} -
- {% endif %} + {% endif %} +
{% if account_backup_pending_hidden %}

A backup is already queued or running.

{% endif %} - {% if account_backup_jobs %} -
- - - - - - {% for job in account_backup_jobs %} - - - - - - - - {% endfor %} - -
RequestedSourceContentsStatusArchive
{{ job.requested_at|date:"j M Y, H:i" }} UTC - {% if job.scheduled_for %} - Scheduled - {% else %} - Manual - {% endif %} - {% if job.includes_mailboxes %}Website, databases, and mail{% else %}Website and databases{% endif %} - {% if job.state == "configured" %} - Ready - {% else %} - {{ job.state|capfirst }} - {% endif %} - - {% if job.state == "configured" %} - {{ job.archive }} - {% if job.pk in website_restore_sources or job.pk in database_restore_sources or job.pk in mailbox_restore_sources %} -
- {% if job.pk in website_restore_sources %} - Restore website - {% endif %} - {% if job.pk in database_restore_sources %} - Restore database - {% endif %} - {% if job.pk in mailbox_restore_sources %} - Restore mailbox - {% endif %} -
- {% endif %} - {% elif job.problem %} - {{ job.problem }} - {% endif %} -
-
- {% elif not account_backup_pending_hidden %} -

No backups requested.

- {% endif %} + {% include "hosting/account_backup_archive_table.html" %} {% if backup_restore_jobs %} diff --git a/src/coulobre/hosting/templates/hosting/backup_retention_form.html b/src/coulobre/hosting/templates/hosting/backup_retention_form.html new file mode 100644 index 0000000..3c4f0ed --- /dev/null +++ b/src/coulobre/hosting/templates/hosting/backup_retention_form.html @@ -0,0 +1,21 @@ +{% extends "hosting/base.html" %} +{% block title %}{{ title }} · Coulobre Panel{% endblock %} +{% block content %} + ← Backup archives +
+
+

{{ title }}

+

{{ account.primary_domain }}{% if archive %} · Backup requested {{ archive.requested_at|date:"j M Y, H:i" }} UTC{% endif %}

+
+
+
+
+ {% csrf_token %} + {{ form.as_div }} +
+ + Cancel +
+
+
+{% endblock %} diff --git a/src/coulobre/hosting/test_backup_retention.py b/src/coulobre/hosting/test_backup_retention.py new file mode 100644 index 0000000..0349adf --- /dev/null +++ b/src/coulobre/hosting/test_backup_retention.py @@ -0,0 +1,384 @@ +import json +from datetime import timedelta +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_backup_retention, +) +from coulobre.account_backup import AccountBackup +from coulobre.account_backup_request import ( + AccountBackupRequest, + expiration_marker, +) +from coulobre.account_backup_retention import ArchiveExpirationRequest +from coulobre.web_node import WebSite + +from .backup_retention import plan_backup_expirations +from .models import ( + AccountBackupExpiration, + AccountBackupJob, + ComponentRestoreJob, + HostingAccount, + WebsiteRestoreJob, +) +from .tasks import ( + ACCOUNT_BACKUP_LEASE, + ACCOUNT_BACKUP_QUEUE, + dispatch_account_backups, + expire_account_backup, + plan_account_backup_expirations, +) + + +@override_settings( + LOCAL_ACCOUNT_BACKUPS=True, + LOCAL_BACKUP_RETENTION=True, + LOCAL_WEBSITE_RESTORE=True, +) +class BackupRetentionTests(TestCase): + @classmethod + def setUpTestData(cls): + cls.operator = get_user_model().objects.create_superuser("operator") + cls.account = HostingAccount.objects.create( + name="Example", + primary_domain="example.net", + scheduled_backups_to_keep=1, + ) + cls.site = WebSite(cls.account.pk, cls.account.primary_domain) + + def setUp(self): + self.client.force_login(self.operator) + self.now = timezone.now() + self.history_url = reverse( + "panel:account_backup_archives", args=[self.account.pk] + ) + self.policy_url = reverse( + "panel:account_backup_retention", args=[self.account.pk] + ) + + def backup(self, age, *, scheduled=True, **overrides): + requested = self.now - timedelta(days=age) + fields = { + "requested_at": requested, + "finished_at": requested, + "scheduled_for": requested if scheduled else None, + "manifest": AccountBackup(self.site, ()).manifest(), + } + return self.account.backup_jobs.create(**(fields | overrides)) + + def test_retention_preserves_manual_protected_failed_and_latest_backups( + self, + ): + manual = self.backup(30, scheduled=False) + protected = self.backup(20, retention_protected=True) + older = self.backup(12) + newest = self.backup(3) + self.backup(2, problem="Backup failed") + self.backup(1, finished_at=None) + + plan_account_backup_expirations() + plan_account_backup_expirations() + job = AccountBackupExpiration.objects.get() + self.assertEqual(job.backup, older) + self.assertEqual(job.keeper_ids, [str(newest.backup_id)]) + self.assertContains( + self.client.get(self.history_url), "Expiration pending" + ) + + with ( + patch.object(expire_account_backup, "apply_async") as publish, + patch("coulobre.hosting.tasks.create_account_backup.apply_async"), + ): + dispatch_account_backups() + publish.assert_called_once_with( + args=[job.pk], queue=ACCOUNT_BACKUP_QUEUE, retry=False + ) + with patch( + "coulobre.hosting.tasks.expire_local_account_backup", + return_value=None, + ) as send: + expire_account_backup(job.pk) + expire_account_backup(job.pk) + send.assert_called_once_with( + ArchiveExpirationRequest( + self.account.pk, older.backup_id, (newest.backup_id,) + ) + ) + self.assertIsNotNone( + self.account.backup_jobs.get(pk=older.pk).expired_at + ) + for backup in (manual, protected, newest): + backup.refresh_from_db() + self.assertIsNone(backup.expired_at) + history = self.client.get(self.history_url) + self.assertContains(history, "Protected from retention") + self.assertContains(history, "Expired") + self.assertNotContains(history, older.archive) + self.assertContains(history, manual.archive) + + def test_restore_and_expiration_cannot_reserve_the_same_archive( + self, + ): + website = self.backup(6) + component = self.backup(5) + candidate = self.backup(4) + self.backup(1) + WebsiteRestoreJob.objects.create( + backup=website, restore_id=uuid4(), operator_username="operator" + ) + ComponentRestoreJob.objects.create( + backup=component, + restore_id=uuid4(), + operator_username="operator", + kind=ComponentRestoreJob.Kind.DATABASE, + resource="cms", + ) + plan_backup_expirations(self.now) + self.assertEqual( + AccountBackupExpiration.objects.get().backup, candidate + ) + url = reverse( + "panel:website_restore", args=[self.account.pk, candidate.pk] + ) + self.assertEqual(self.client.get(url).status_code, 404) + + def test_unconfirmed_expiration_remains_pending_and_retries_the_same_plan( + self, + ): + backup = self.backup(3) + self.backup(1) + plan_backup_expirations(self.now) + job = AccountBackupExpiration.objects.get(backup=backup) + with patch( + "coulobre.hosting.tasks.expire_local_account_backup", + side_effect=[TimeoutError(), None], + ) as send: + expire_account_backup(job.pk) + expire_account_backup(job.pk) + job.refresh_from_db() + self.assertIsNone(job.finished_at) + self.assertIn("worker will retry", job.problem) + self.assertFalse( + AccountBackupJob.objects.get( + pk=backup.pk + ).archive_is_restorable + ) + self.assertEqual(send.call_count, 1) + AccountBackupExpiration.objects.filter(pk=job.pk).update( + started_at=self.now - ACCOUNT_BACKUP_LEASE + ) + expire_account_backup(job.pk) + self.assertEqual(send.call_args_list[0], send.call_args_list[1]) + backup.refresh_from_db() + self.assertIsNotNone(backup.expired_at) + + def test_a_blocked_expiration_leaves_the_archive_restorable(self): + backup = self.backup(3) + self.backup(1) + plan_backup_expirations(self.now) + job = AccountBackupExpiration.objects.get(backup=backup) + with patch( + "coulobre.hosting.tasks.expire_local_account_backup", + return_value="A newer archive is missing.", + ): + expire_account_backup(job.pk) + job.refresh_from_db() + self.assertEqual(job.state, "failed") + self.assertTrue( + AccountBackupJob.objects.get(pk=backup.pk).archive_is_restorable + ) + self.assertContains( + self.client.get(self.history_url), "A newer archive is missing." + ) + + def test_protection_and_policy_changes_cancel_unstarted_expirations(self): + backup = self.backup(3) + self.backup(2) + self.backup(1) + plan_backup_expirations(self.now) + job = AccountBackupExpiration.objects.get(backup=backup) + url = reverse( + "panel:account_backup_protection", + args=[self.account.pk, backup.pk], + ) + self.assertRedirects( + self.client.post(url, {"protected": "1"}), self.history_url + ) + backup.refresh_from_db() + job.refresh_from_db() + self.assertTrue(backup.retention_protected) + self.assertIsNotNone(job.finished_at) + + plan_backup_expirations(self.now) + pending = AccountBackupExpiration.objects.get(finished_at__isnull=True) + self.assertRedirects( + self.client.post(self.policy_url, {"count": ""}), self.history_url + ) + self.account.refresh_from_db() + pending.refresh_from_db() + self.assertIsNone(self.account.scheduled_backups_to_keep) + self.assertIsNotNone(pending.finished_at) + self.assertContains( + self.client.get(self.history_url), + "Automatic expiration is disabled", + ) + + def test_policy_and_protection_have_a_separate_operator_permission(self): + backup = self.backup(3) + url = reverse( + "panel:account_backup_protection", + args=[self.account.pk, backup.pk], + ) + user = get_user_model().objects.create_user("limited") + permissions = Permission.objects.filter( + content_type__app_label="hosting" + ) + user.user_permissions.add( + *permissions.filter( + codename__in=( + "view_hostingaccount", + "view_webprovisioningplan", + "view_hostingdatabase", + "add_accountbackupjob", + "manage_backup_retention", + ) + ) + ) + self.client.force_login(user) + self.assertEqual( + self.client.post(self.policy_url, {"count": 2}).status_code, 403 + ) + self.assertEqual( + self.client.post(url, {"protected": "1"}).status_code, 403 + ) + self.assertNotContains( + self.client.get(self.history_url), "Manage retention" + ) + user.user_permissions.add( + permissions.get(codename="view_hostingmailbox") + ) + self.assertContains( + self.client.post(self.policy_url, {"count": 0}), + "greater than or equal to 1", + ) + self.assertRedirects( + self.client.post(self.policy_url, {"count": 2}), self.history_url + ) + self.assertContains( + self.client.get(self.history_url), "Keep 2 scheduled backups" + ) + + def test_archive_history_paginates_old_archives(self): + oldest = self.backup(30) + for age in range(26): + self.backup(age, scheduled=False) + self.assertNotContains( + self.client.get(self.history_url), oldest.archive + ) + self.assertContains( + self.client.get(self.history_url + "?page=2"), oldest.archive + ) + + @override_settings(LOCAL_BACKUP_RETENTION=False) + def test_server_opt_in_is_needed_to_manage_and_plan_retention(self): + self.backup(3) + self.backup(1) + self.assertEqual(self.client.get(self.policy_url).status_code, 404) + plan_account_backup_expirations() + self.assertFalse(AccountBackupExpiration.objects.exists()) + + +class NodeArchiveRetentionTests(SimpleTestCase): + def setUp(self): + self.directory = Path(self.enterContext(TemporaryDirectory())) + self.enterContext( + patch.object( + account_backup_request, "BACKUP_DIRECTORY", self.directory + ) + ) + self.enterContext( + patch.object( + account_backup, "private_path", side_effect=lambda path: path + ) + ) + self.enterContext(patch.object(account_backup, "check_root_file")) + self.enterContext( + patch.object(account_backup_retention, "check_root_file") + ) + self.enterContext( + patch.object(account_backup_request.os, "geteuid", return_value=0) + ) + self.enterContext(patch("coulobre.node_files.require_root_directory")) + self.enterContext( + patch.dict("os.environ", {"COULOBRE_LOCAL_BACKUP_RETENTION": "1"}) + ) + self.backup = AccountBackup(WebSite(42, "example.net"), ()) + self.target_id = uuid4() + self.keeper_id = uuid4() + self.target = account_backup_request.backup_archive(42, self.target_id) + self.keeper = account_backup_request.backup_archive(42, self.keeper_id) + self.request = ArchiveExpirationRequest( + 42, self.target_id, (self.keeper_id,) + ) + + def write_archive(self, path, backup): + with ZipFile(path, "w") as bundle: + bundle.writestr("manifest.json", json.dumps(backup.manifest())) + bundle.writestr("website.tar.gz", b"fixture") + + def test_missing_or_foreign_keeper_preserves_the_candidate(self): + self.write_archive(self.target, self.backup) + reply = account_backup_retention.expire_requested_archive(self.request) + self.assertFalse(reply["removed"]) + self.assertTrue(self.target.exists()) + self.write_archive( + self.keeper, AccountBackup(WebSite(43, "other.net"), ()) + ) + reply = account_backup_retention.expire_requested_archive(self.request) + self.assertFalse(reply["removed"]) + self.assertIn("different account", reply["reason"]) + self.assertTrue(self.target.exists()) + self.assertFalse(expiration_marker(self.target).exists()) + + def test_expiration_is_replayable_and_creation_cannot_recreate_the_archive( + self, + ): + self.write_archive(self.target, self.backup) + self.write_archive(self.keeper, self.backup) + request = account_backup_request.parse_backup_request( + self.request.manifest() + ) + for _ in range(2): + reply = account_backup_request.apply_backup_request(request) + self.assertEqual(reply, {"removed": True, "reason": None}) + self.assertTrue(self.keeper.exists()) + self.assertFalse(self.target.exists()) + self.assertTrue(expiration_marker(self.target).exists()) + with self.assertRaisesMessage(ValueError, "has expired"): + account_backup_request.ensure_requested_archive( + AccountBackupRequest(self.target_id, self.backup) + ) + + def test_disabled_node_cannot_expire_archives(self): + self.write_archive(self.target, self.backup) + self.write_archive(self.keeper, self.backup) + with patch.dict( + "os.environ", {"COULOBRE_LOCAL_BACKUP_RETENTION": "0"} + ): + reply = account_backup_retention.expire_requested_archive( + self.request + ) + self.assertFalse(reply["removed"]) + self.assertTrue(self.target.exists()) diff --git a/src/coulobre/hosting/test_panel_account_backups.py b/src/coulobre/hosting/test_panel_account_backups.py index 30832ab..d4d6953 100644 --- a/src/coulobre/hosting/test_panel_account_backups.py +++ b/src/coulobre/hosting/test_panel_account_backups.py @@ -96,6 +96,7 @@ class PanelAccountBackupTests(TestCase): ) page = self.client.get(self.account.get_absolute_url()) self.assertContains(page, "Ready") + self.assertContains(page, "2.0\u00a0KB") self.assertContains(page, job.archive) self.client.post(self.request_url) self.assertEqual(self.account.backup_jobs.count(), 2) diff --git a/src/coulobre/hosting/urls.py b/src/coulobre/hosting/urls.py index 8daa711..0ce5525 100644 --- a/src/coulobre/hosting/urls.py +++ b/src/coulobre/hosting/urls.py @@ -41,6 +41,21 @@ urlpatterns = [ views.RequestAccountBackup.as_view(), name="account_backup_create", ), + path( + "accounts//backups/archives/", + views.AccountBackupArchiveList.as_view(), + name="account_backup_archives", + ), + path( + "accounts//backups/retention/", + views.EditBackupRetention.as_view(), + name="account_backup_retention", + ), + path( + "accounts//backups//protection/", + views.EditBackupProtection.as_view(), + name="account_backup_protection", + ), path( "accounts//backups/schedule/", views.EditAccountBackupSchedule.as_view(), diff --git a/src/coulobre/hosting/views.py b/src/coulobre/hosting/views.py index 3ed7279..ae418b9 100644 --- a/src/coulobre/hosting/views.py +++ b/src/coulobre/hosting/views.py @@ -43,6 +43,8 @@ from .access import ( from .account_backup_forms import ( SCHEDULE_FIELDS, AccountBackupScheduleForm, + BackupProtectionForm, + BackupRetentionForm, ComponentRestoreForm, WebsiteRestoreForm, ) @@ -59,6 +61,7 @@ from .backup_restores import ( queue_component_restore, queue_website_restore, ) +from .backup_retention import change_backup_retention, protect_backup from .dns_forms import DnsZoneEditForm, DnsZoneForm, format_txt_record from .dns_publication import queue_dns_publication from .impersonation import ( @@ -126,6 +129,11 @@ MANAGE_BACKUP_SCHEDULE = ( *MANAGE_ACCOUNT_BACKUPS, "hosting.change_accountbackupschedule", ) +MANAGE_BACKUP_RETENTION = ( + *MANAGE_ACCOUNT_BACKUPS, + VIEW_MAILBOXES, + "hosting.manage_backup_retention", +) RESTORE_WEBSITE = (*MANAGE_ACCOUNT_BACKUPS, "hosting.add_websiterestorejob") COMPONENT_RESTORE_PERMISSIONS = { RestoreKind.DATABASE: ( @@ -326,15 +334,14 @@ class AccountDetail(TenantScopeMixin, PermissionRequiredMixin, DetailView): and not tenant and user.has_perms(MANAGE_ACCOUNT_BACKUPS) ): - jobs = list( - self.object.backup_jobs.order_by("-requested_at", "-pk")[:10] - ) can_view_mailboxes = user.has_perm(VIEW_MAILBOXES) context["show_account_backups"] = True - visible_jobs = ( - jobs - if can_view_mailboxes - else [job for job in jobs if not job.includes_mailboxes] + context["manage_backup_retention"] = ( + settings.LOCAL_BACKUP_RETENTION + and user.has_perms(MANAGE_BACKUP_RETENTION) + ) + visible_jobs = list( + visible_account_backups(self.object, user)[:10] ) context["account_backup_jobs"] = visible_jobs context.update( @@ -342,12 +349,14 @@ class AccountDetail(TenantScopeMixin, PermissionRequiredMixin, DetailView): self.object, user, visible_jobs, can_view_mailboxes ) ) - pending = next( - (job for job in jobs if job.finished_at is None), None - ) + pending = self.object.backup_jobs.filter( + finished_at__isnull=True + ).first() context["account_backup_pending"] = pending is not None context["account_backup_pending_hidden"] = ( - pending is not None and pending not in visible_jobs + pending is not None + and pending.includes_mailboxes + and not can_view_mailboxes ) context["account_backup_allow_mail"] = ( settings.LOCAL_ACCOUNT_BACKUP_MAIL and can_view_mailboxes @@ -526,6 +535,135 @@ class RequestAccountBackup(OperatorOnlyMixin, PermissionRequiredMixin, View): return redirect("panel:account", pk=pk) +def visible_account_backups(account, user): + backups = account.backup_jobs.select_related("expiration").order_by( + "-requested_at", "-pk" + ) + if not user.has_perm(VIEW_MAILBOXES): + backups = backups.exclude(manifest__has_key="mailboxes") + return backups + + +class AccountBackupArchiveList( + OperatorOnlyMixin, PermissionRequiredMixin, ListView +): + permission_required = MANAGE_ACCOUNT_BACKUPS + template_name = "hosting/account_backup_archives.html" + context_object_name = "account_backup_jobs" + paginate_by = 25 + + def dispatch(self, request, *args, **kwargs): + if not settings.LOCAL_ACCOUNT_BACKUPS: + raise Http404 + return super().dispatch(request, *args, **kwargs) + + @cached_property + def account(self): + return get_object_or_404(HostingAccount, pk=self.kwargs["pk"]) + + def get_queryset(self): + return visible_account_backups(self.account, self.request.user) + + def get_context_data(self, **kwargs): + context = super().get_context_data(account=self.account, **kwargs) + user = self.request.user + context["manage_backup_retention"] = ( + settings.LOCAL_BACKUP_RETENTION + and user.has_perms(MANAGE_BACKUP_RETENTION) + ) + context.update( + backup_restore_context( + self.account, + user, + list(context["account_backup_jobs"]), + user.has_perm(VIEW_MAILBOXES), + ) + ) + return context + + +class BackupRetentionView( + OperatorOnlyMixin, PermissionRequiredMixin, FormView +): + permission_required = MANAGE_BACKUP_RETENTION + template_name = "hosting/backup_retention_form.html" + + def dispatch(self, request, *args, **kwargs): + if not ( + settings.LOCAL_ACCOUNT_BACKUPS and settings.LOCAL_BACKUP_RETENTION + ): + raise Http404 + return super().dispatch(request, *args, **kwargs) + + @cached_property + def account(self): + return get_object_or_404(HostingAccount, pk=self.kwargs["pk"]) + + def get_success_url(self): + return reverse("panel:account_backup_archives", args=[self.account.pk]) + + def get_context_data(self, **kwargs): + return super().get_context_data( + account=self.account, + title=self.title, + back_url=self.get_success_url(), + **kwargs, + ) + + +class EditBackupRetention(BackupRetentionView): + form_class = BackupRetentionForm + title = "Backup retention" + + def get_initial(self): + return {"count": self.account.scheduled_backups_to_keep} + + def form_valid(self, form): + try: + change_backup_retention( + self.account.pk, form.cleaned_data["count"] + ) + except HostingAccount.DoesNotExist: + raise Http404 from None + return super().form_valid(form) + + +class EditBackupProtection(BackupRetentionView): + form_class = BackupProtectionForm + title = "Archive protection" + + @cached_property + def backup(self): + backup = get_object_or_404( + self.account.backup_jobs, + pk=self.kwargs["backup_pk"], + scheduled_for__isnull=False, + ) + if backup.state != "configured" or backup.expired_at is not None: + raise Http404 + return backup + + def get_initial(self): + return {"protected": "1" if self.backup.retention_protected else "0"} + + def get_context_data(self, **kwargs): + return super().get_context_data(archive=self.backup, **kwargs) + + def form_valid(self, form): + try: + protect_backup( + self.account.pk, + self.backup.pk, + protected=form.cleaned_data["protected"], + ) + except (HostingAccount.DoesNotExist, AccountBackupJob.DoesNotExist): + raise Http404 from None + except ValidationError as error: + form.add_error(None, error) + return self.form_invalid(form) + return super().form_valid(form) + + def backup_restore_context(account, user, backups, can_view_mailboxes): context = {} history = [] @@ -581,11 +719,11 @@ class BackupRestoreView(OperatorOnlyMixin, PermissionRequiredMixin, FormView): def get_backup(self): backup = get_object_or_404( - AccountBackupJob.objects.select_related("account"), + AccountBackupJob.objects.select_related("account", "expiration"), pk=self.kwargs["backup_pk"], account_id=self.kwargs["pk"], ) - if backup.state != "configured": + if not backup.archive_is_restorable: raise Http404 if backup.includes_mailboxes and not self.request.user.has_perm( VIEW_MAILBOXES