Configure and monitor off-site copies in the hosting panel
Coulobre Panel CI / Checks (Python 3.12) (pull_request) Canceled after 0s
Coulobre Panel CI / Checks (Python 3.14) (pull_request) Canceled after 0s

This commit is contained in:
parkel committed 2026-11-22 16:14:55 +01:00
1 parent ab16c9db62
commit 0b93754e4c
8 files changed
+428 -3

No files matched your search

+1
View File
@@ -50,6 +50,7 @@ COULOBRE_BROKER_URL=amqp://coulobre:@127.0.0.1:5672/coulobre
# COULOBRE_LOCAL_ACCOUNT_BACKUP_MAIL=1 # COULOBRE_LOCAL_ACCOUNT_BACKUP_MAIL=1
# COULOBRE_REMOTE_ACCOUNT_BACKUP_MAIL=1 # COULOBRE_REMOTE_ACCOUNT_BACKUP_MAIL=1
# COULOBRE_LOCAL_BACKUP_RETENTION=1 # COULOBRE_LOCAL_BACKUP_RETENTION=1
# COULOBRE_OFFSITE_BACKUP_DESTINATIONS='{"vault":"Off-site vault"}'
# COULOBRE_LOCAL_WEBSITE_RESTORE=1 # COULOBRE_LOCAL_WEBSITE_RESTORE=1
# COULOBRE_LOCAL_DATABASE_RESTORE=1 # COULOBRE_LOCAL_DATABASE_RESTORE=1
# COULOBRE_LOCAL_MAILBOX_RESTORE=1 # COULOBRE_LOCAL_MAILBOX_RESTORE=1
+90
View File
@@ -991,6 +991,96 @@ Expired entries stay in the history and lose their restore actions. Keep
the corresponding `.expired` records beside the ZIPs to prevent a late the corresponding `.expired` records beside the ZIPs to prevent a late
worker delivery from recreating an expired archive. worker delivery from recreating an expired archive.
#### Copy scheduled account backups off-site
Coulobre can send scheduled archives to an encrypted restic repository over
SFTP. On the backup node, install restic and OpenSSH and create a directory
for each destination. This example uses the destination ID `vault`.
[Restic SFTP repository setup](https://restic.readthedocs.io/en/stable/030_preparing_a_new_repo.html#sftp)
```sh
sudo apt install restic openssh-client
sudo install -d -m 0700 /etc/coulobre/offsite/vault
sudo ssh-keygen -t ed25519 -N '' -f /etc/coulobre/offsite/vault/identity
```
Authorize the public key for a dedicated SFTP login that has access to the
repository. Place the destination files in the directory with root
ownership and mode `0600`.
| File | Contents |
| --- | --- |
| `repository` | A line such as `sftp:coulobre-offsite:repository`. Here `repository` is relative to the SFTP user's directory. |
| `password` | The restic repository password. Store a recovery copy separately from the backup node. |
| `ssh_config` | A `Host coulobre-offsite` block with the storage server's `HostName`, `User`, and optional `Port`. Set `ConnectTimeout 10`, `ServerAliveInterval 30`, and `ServerAliveCountMax 3`. |
| `identity` | The dedicated private key generated above. |
| `known_hosts` | The independently verified SSH host key for the storage server. |
Create a new repository if needed, then verify access from the backup node.
```sh
profile=/etc/coulobre/offsite/vault
ssh_options="-F $profile/ssh_config -i $profile/identity"
ssh_options="$ssh_options -o UserKnownHostsFile=$profile/known_hosts"
ssh_options="$ssh_options -o GlobalKnownHostsFile=/dev/null"
ssh_options="$ssh_options -o StrictHostKeyChecking=yes -o BatchMode=yes -o IdentitiesOnly=yes"
sudo restic --repository-file "$profile/repository" \
--password-file "$profile/password" -o "sftp.args=$ssh_options" init
sudo /opt/coulobre/bin/coulobre-account-backup verify-offsite vault
```
Set `COULOBRE_OFFSITE_BACKUP_DESTINATIONS='{"vault":"Off-site vault"}'` in
`/etc/coulobre/panel.env`. This setting contains IDs and labels. Each ID
maps to a directory under `/etc/coulobre/offsite` on the backup node.
```sh
sudo groupadd --system coulobre-offsite-requests
sudo useradd --system --user-group --no-create-home --home-dir /nonexistent \
--shell /usr/sbin/nologin coulobre-offsite-worker
sudo install -m 0644 deploy/systemd/coulobre-account-offsite.socket \
deploy/systemd/coulobre-account-offsite@.service \
deploy/systemd/coulobre-offsite-worker.service /etc/systemd/system/
panel_manage migrate --noinput
sudo systemctl daemon-reload
sudo systemctl enable --now coulobre-offsite-worker.service
sudo systemctl restart coulobre-panel coulobre-worker coulobre-beat
```
Choose the destination in **Backup schedule**. The choice applies to future
scheduled backups. The archive history shows transfer status. A copy becomes
**Verified** after the worker reads it back from restic and verifies its
size and SHA-256 checksum. Allow time and bandwidth for both the upload
and verification within the 30-minute transfer deadline. An interrupted
transfer reuses an existing snapshot with the same backup ID and verifies
it again. The worker makes up to five attempts before requiring a manual
retry. Operators with **Can change offsite backup transfer** can retry a
failed copy from the archive history. Add `offsite-backups` to the local
service health list to monitor the worker.
Archives awaiting verification stay on the backup node and do not count
toward the eligible local retention set. Once verified, they follow the
existing local schedule and protection rules. Manage remote snapshot
retention in restic on the storage side. Assign a new destination ID when
switching repositories. Keep the original profile and recovery credentials
for as long as you retain copies in that repository.
To recover a copy, take its destination ID, account ID, and backup ID from
the archive history. Run the recovery command on a node with the
destination profile. It looks up the snapshot by backup ID and verifies
the checksum in its authenticated metadata before creating the output file.
```sh
sudo install -d -m 0700 /srv/coulobre-recovery
sudo /opt/coulobre/bin/coulobre-account-backup recover-offsite vault 42 \
123e4567-e89b-12d3-a456-426614174000 /srv/coulobre-recovery/account.zip
sudo /opt/coulobre/bin/coulobre-account-backup unpack \
/srv/coulobre-recovery/account.zip /srv/coulobre-recovery/resources
```
The remote snapshot stores the archive filename and backup ID tag. With
the repository credentials, use `restic snapshots --json` to find them
when recovering without the original panel database.
#### Restore from local account backups in the panel #### Restore from local account backups in the panel
Enable local account backups first. Install the restore socket and give the Enable local account backups first. Install the restore socket and give the
@@ -1,6 +1,7 @@
from uuid import uuid4 from uuid import uuid4
from django import forms from django import forms
from django.conf import settings
from django.core.exceptions import ValidationError from django.core.exceptions import ValidationError
from coulobre.account_backup_retention import MAX_RETAINED_BACKUPS from coulobre.account_backup_retention import MAX_RETAINED_BACKUPS
@@ -18,6 +19,7 @@ SCHEDULE_FIELDS = (
"weekday", "weekday",
"time", "time",
"include_mailboxes", "include_mailboxes",
"offsite_destination",
) )
@@ -47,6 +49,15 @@ class AccountBackupScheduleForm(forms.Form):
self.allow_mail = allow_mail self.allow_mail = allow_mail
if not allow_mail and not self.initial.get("include_mailboxes"): if not allow_mail and not self.initial.get("include_mailboxes"):
del self.fields["include_mailboxes"] del self.fields["include_mailboxes"]
destinations = settings.OFFSITE_BACKUP_DESTINATIONS
current = self.initial.get("offsite_destination")
if destinations or current:
choices = [("", "Local archive only"), *destinations.items()]
if current and current not in destinations:
choices.append((current, f"{current} (unavailable)"))
self.fields["offsite_destination"] = forms.ChoiceField(
choices=choices, required=False, label="Off-site destination"
)
def clean(self): def clean(self):
cleaned = super().clean() cleaned = super().clean()
@@ -28,6 +28,28 @@
{% else %} {% else %}
{{ job.state|capfirst }} {{ job.state|capfirst }}
{% endif %} {% endif %}
{% with transfer=job.offsite_transfer %}
{% if transfer %}
<div>Off-site · {{ transfer.label }} · {{ transfer.status }}</div>
{% if transfer.verified_at %}
<div>{{ transfer.verified_at|date:"j M Y, H:i" }} UTC</div>
<details>
<summary>Recovery details</summary>
<div>Backup ID <code>{{ job.backup_id }}</code></div>
<div>Account ID <code>{{ job.account_id }}</code></div>
<div>Destination ID <code>{{ transfer.destination }}</code></div>
</details>
{% elif transfer.problem %}
<div>{{ transfer.problem }}</div>
{% if can_retry_offsite and transfer.status == "Failed" %}
<form method="post" action="{% url 'panel:retry_offsite_backup' account.pk job.pk %}">
{% csrf_token %}
<button type="submit" class="button secondary">Retry off-site copy</button>
</form>
{% endif %}
{% endif %}
{% endif %}
{% endwith %}
</td> </td>
<td> <td>
{% if job.expired_at %} {% if job.expired_at %}
@@ -0,0 +1,266 @@
import json
from datetime import timedelta
from pathlib import Path
from unittest.mock import patch
from uuid import uuid4
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.account_backup import AccountBackup
from coulobre.offsite_backup import OffsiteBackupRequest, destination_labels
from coulobre.offsite_node import OffsiteRepositoryError, Repository
from coulobre.web_node import WebSite
from .account_backups import queue_account_backup, queue_due_account_backups
from .backup_retention import plan_backup_expirations
from .models import (
AccountBackupExpiration,
HostingAccount,
OffsiteBackupTransfer,
)
from .offsite_backups import MAX_ATTEMPTS, OFFSITE_BACKUP_QUEUE
from .tasks import dispatch_offsite_backups, transfer_offsite_backup
class OffsiteRepositoryTests(SimpleTestCase):
def test_destination_profiles_and_requests_are_bounded(self):
request = OffsiteBackupRequest(42, uuid4(), "vault")
self.assertEqual(
OffsiteBackupRequest.from_manifest(request.manifest()), request
)
for destination in ("../vault", "elsewhere:repo", "A", "two words"):
with (
self.subTest(destination=destination),
self.assertRaises(ValueError),
):
destination_labels({destination: "Fixture"})
self.assertNotIn("password", request.manifest())
def test_snapshot_lookup_checks_archive_identity_and_checksum_metadata(
self,
):
request = OffsiteBackupRequest(42, uuid4(), "vault")
repository = Repository(Path("/etc/coulobre/offsite/vault"))
entry = {
"id": "a" * 64,
"paths": [f"/{request.archive_name}"],
"tags": [request.tag, "coulobre-sha256-" + "b" * 64],
}
with patch.object(
Repository, "run", return_value=json.dumps([entry])
) as restic:
self.assertEqual(
repository.snapshot(request), ("a" * 64, "b" * 64)
)
restic.assert_called_once_with(
"--json", "snapshots", "--tag", request.tag, capture=True
)
for entries in ([entry, entry], [entry | {"paths": ["/another.zip"]}]):
with (
patch.object(
Repository, "run", return_value=json.dumps(entries)
),
self.assertRaises(OffsiteRepositoryError),
):
repository.snapshot(request)
@override_settings(
LOCAL_ACCOUNT_BACKUPS=True,
LOCAL_BACKUP_RETENTION=True,
OFFSITE_BACKUP_DESTINATIONS={"vault": "Off-site vault"},
)
class OffsiteBackupWorkflowTests(TestCase):
@classmethod
def setUpTestData(cls):
cls.operator = get_user_model().objects.create_superuser("operator")
cls.account = HostingAccount.objects.create(
name="Off-site fixture",
primary_domain="example.test",
scheduled_backups_to_keep=1,
)
def setUp(self):
self.client.force_login(self.operator)
self.now = timezone.now()
self.history = reverse(
"panel:account_backup_archives", args=[self.account.pk]
)
self.schedule = reverse(
"panel:account_backup_schedule", args=[self.account.pk]
)
def archive(self, *, age=0, **values):
requested = self.now - timedelta(days=age)
spec = AccountBackup(
WebSite(self.account.pk, self.account.primary_domain), ()
)
return self.account.backup_jobs.create(
**(
{
"manifest": spec.manifest(),
"finished_at": requested,
"requested_at": requested,
"scheduled_for": requested,
}
| values
)
)
def transfer(self, archive=None, **values):
return OffsiteBackupTransfer.objects.create(
backup=self.archive() if archive is None else archive,
destination="vault",
next_attempt_at=self.now,
**values,
)
def test_only_scheduled_backups_capture_the_configured_destination(self):
response = self.client.post(
self.schedule,
{
"enabled": "on",
"frequency": "daily",
"time": "10:00",
"offsite_destination": "vault",
},
)
self.assertRedirects(response, self.account.get_absolute_url())
schedule = self.account.backup_schedule
self.assertEqual(schedule.offsite_destination, "vault")
schedule.next_run_at = self.now
schedule.save(update_fields=["next_run_at"])
queue_due_account_backups(self.now)
offsite = OffsiteBackupTransfer.objects.get()
self.assertEqual(offsite.backup.scheduled_for, self.now)
self.assertEqual(offsite.destination, "vault")
offsite.backup.finished_at = self.now
offsite.backup.save(update_fields=["finished_at"])
queue_account_backup(self.account.pk)
self.assertEqual(OffsiteBackupTransfer.objects.count(), 1)
self.assertTrue(
self.account.backup_jobs.filter(
scheduled_for__isnull=True
).exists()
)
self.assertContains(
self.client.post(
self.schedule,
{
"enabled": "on",
"frequency": "daily",
"time": "10:00",
"offsite_destination": "../../elsewhere",
},
),
"Select a valid choice",
)
def test_only_finished_local_archives_are_dispatched(self):
ready = self.transfer()
self.transfer(self.archive(finished_at=None))
self.transfer(self.archive(problem="Local backup failed"))
self.transfer(self.archive(expired_at=self.now))
with patch.object(transfer_offsite_backup, "apply_async") as publish:
dispatch_offsite_backups.run()
publish.assert_called_once_with(
args=[ready.pk],
queue=OFFSITE_BACKUP_QUEUE,
retry=False,
)
def test_retry_is_bounded_and_duplicate_delivery_does_not_reupload(self):
transfer = self.transfer()
with patch(
"coulobre.hosting.offsite_backups.apply_offsite_transfer",
side_effect=OSError("secret fixture"),
) as send:
for attempt in range(MAX_ATTEMPTS):
OffsiteBackupTransfer.objects.filter(pk=transfer.pk).update(
next_attempt_at=self.now
)
transfer_offsite_backup.run(transfer.pk)
transfer_offsite_backup.run(transfer.pk)
self.assertEqual(send.call_count, attempt + 1)
transfer.refresh_from_db()
self.assertIsNotNone(transfer.finished_at)
self.assertNotIn("secret fixture", transfer.problem)
self.assertContains(
self.client.get(self.history), "Retry off-site copy"
)
retry = reverse(
"panel:retry_offsite_backup",
args=[self.account.pk, transfer.backup_id],
)
self.assertRedirects(self.client.post(retry), self.history)
transfer.refresh_from_db()
self.assertEqual(transfer.attempts, 0)
with patch(
"coulobre.hosting.offsite_backups.apply_offsite_transfer",
return_value=("a" * 64, "b" * 64),
) as send:
transfer_offsite_backup.run(transfer.pk)
transfer_offsite_backup.run(transfer.pk)
send.assert_called_once()
transfer.refresh_from_db()
self.assertEqual(transfer.snapshot, "a" * 64)
self.assertEqual(transfer.sha256, "b" * 64)
self.assertIsNotNone(transfer.verified_at)
self.assertContains(
self.client.get(self.history), "Off-site vault · Verified"
)
self.assertEqual(self.client.post(retry).status_code, 409)
def test_retention_keeps_the_source_and_waits_for_a_verified_successor(
self,
):
previous = self.archive(age=3)
waiting = self.transfer(
self.archive(age=2), problem="Unavailable", finished_at=self.now
)
newest = self.transfer(self.archive(age=1))
plan_backup_expirations(self.now)
self.assertFalse(AccountBackupExpiration.objects.exists())
newest.verified_at = newest.finished_at = self.now
newest.save(update_fields=["verified_at", "finished_at"])
plan_backup_expirations(self.now)
expiration = AccountBackupExpiration.objects.get()
self.assertEqual(expiration.backup, previous)
self.assertEqual(expiration.keeper_ids, [str(newest.backup.backup_id)])
self.assertFalse(
AccountBackupExpiration.objects.filter(
backup=waiting.backup
).exists()
)
def test_retry_permission_and_account_scope(self):
transfer = self.transfer(finished_at=self.now, problem="Failed")
user = get_user_model().objects.create_user("limited-operator")
user.user_permissions.add(
*Permission.objects.filter(
codename__in=[
"view_hostingaccount",
"view_webprovisioningplan",
"view_hostingdatabase",
"add_accountbackupjob",
]
)
)
self.client.force_login(user)
retry = reverse(
"panel:retry_offsite_backup",
args=[self.account.pk, transfer.backup_id],
)
self.assertEqual(self.client.post(retry).status_code, 403)
self.client.force_login(self.operator)
other = HostingAccount.objects.create(
name="Foreign", primary_domain="foreign.test"
)
scoped = reverse(
"panel:retry_offsite_backup", args=[other.pk, transfer.backup_id]
)
self.assertEqual(self.client.post(scoped).status_code, 404)
+5
View File
@@ -184,6 +184,11 @@ urlpatterns = [
views.AccountBackupArchiveList.as_view(), views.AccountBackupArchiveList.as_view(),
name="account_backup_archives", name="account_backup_archives",
), ),
path(
"accounts/<int:pk>/backups/<int:backup_pk>/offsite/retry/",
views.RetryOffsiteBackup.as_view(),
name="retry_offsite_backup",
),
path( path(
"accounts/<int:pk>/backups/retention/", "accounts/<int:pk>/backups/retention/",
views.EditBackupRetention.as_view(), views.EditBackupRetention.as_view(),
+29 -3
View File
@@ -103,6 +103,7 @@ from .models import (
WebsiteDomain, WebsiteDomain,
WebsiteRestoreJob, WebsiteRestoreJob,
) )
from .offsite_backups import retry_offsite_transfer
from .php_settings import ( from .php_settings import (
SitePhpSettingsForm, SitePhpSettingsForm,
last_applied_php_settings, last_applied_php_settings,
@@ -188,6 +189,10 @@ MANAGE_BACKUP_SCHEDULE = (
*MANAGE_ACCOUNT_BACKUPS, *MANAGE_ACCOUNT_BACKUPS,
"hosting.change_accountbackupschedule", "hosting.change_accountbackupschedule",
) )
RETRY_OFFSITE_BACKUP = (
*MANAGE_ACCOUNT_BACKUPS,
"hosting.change_offsitebackuptransfer",
)
MANAGE_BACKUP_RETENTION = ( MANAGE_BACKUP_RETENTION = (
*MANAGE_ACCOUNT_BACKUPS, *MANAGE_ACCOUNT_BACKUPS,
VIEW_MAILBOXES, VIEW_MAILBOXES,
@@ -522,6 +527,7 @@ class AccountDetail(TenantScopeMixin, PermissionRequiredMixin, DetailView):
): ):
can_view_mailboxes = user.has_perm(VIEW_MAILBOXES) can_view_mailboxes = user.has_perm(VIEW_MAILBOXES)
context["show_account_backups"] = True context["show_account_backups"] = True
context["can_retry_offsite"] = user.has_perms(RETRY_OFFSITE_BACKUP)
context["manage_backup_retention"] = ( context["manage_backup_retention"] = (
settings.LOCAL_BACKUP_RETENTION settings.LOCAL_BACKUP_RETENTION
and user.has_perms(MANAGE_BACKUP_RETENTION) and user.has_perms(MANAGE_BACKUP_RETENTION)
@@ -998,9 +1004,9 @@ class RequestAccountBackup(OperatorOnlyMixin, PermissionRequiredMixin, View):
def visible_account_backups(account, user): def visible_account_backups(account, user):
backups = account.backup_jobs.select_related("expiration").order_by( backups = account.backup_jobs.select_related(
"-requested_at", "-pk" "expiration", "offsite_transfer"
) ).order_by("-requested_at", "-pk")
if not user.has_perm(VIEW_MAILBOXES): if not user.has_perm(VIEW_MAILBOXES):
backups = backups.exclude(manifest__has_key="mailboxes") backups = backups.exclude(manifest__has_key="mailboxes")
return backups return backups
@@ -1029,6 +1035,7 @@ class AccountBackupArchiveList(
def get_context_data(self, **kwargs): def get_context_data(self, **kwargs):
context = super().get_context_data(account=self.account, **kwargs) context = super().get_context_data(account=self.account, **kwargs)
user = self.request.user user = self.request.user
context["can_retry_offsite"] = user.has_perms(RETRY_OFFSITE_BACKUP)
context["manage_backup_retention"] = ( context["manage_backup_retention"] = (
settings.LOCAL_BACKUP_RETENTION settings.LOCAL_BACKUP_RETENTION
and user.has_perms(MANAGE_BACKUP_RETENTION) and user.has_perms(MANAGE_BACKUP_RETENTION)
@@ -1048,6 +1055,25 @@ class AccountBackupArchiveList(
return context return context
class RetryOffsiteBackup(OperatorOnlyMixin, PermissionRequiredMixin, View):
permission_required = RETRY_OFFSITE_BACKUP
def post(self, request, pk, backup_pk):
if not settings.LOCAL_ACCOUNT_BACKUPS:
raise Http404
account = get_object_or_404(HostingAccount, pk=pk)
backup = get_object_or_404(
visible_account_backups(account, request.user),
pk=backup_pk,
offsite_transfer__isnull=False,
)
try:
retry_offsite_transfer(backup.offsite_transfer)
except ValidationError as error:
return provisioning_conflict(error)
return redirect("panel:account_backup_archives", pk=pk)
class BackupRetentionView( class BackupRetentionView(
OperatorOnlyMixin, PermissionRequiredMixin, FormView OperatorOnlyMixin, PermissionRequiredMixin, FormView
): ):
+4
View File
@@ -18,6 +18,10 @@ SERVICES = {
"Coulobre website job worker", "Coulobre website job worker",
"coulobre-website-job-worker.service", "coulobre-website-job-worker.service",
), ),
"offsite-backups": (
"Coulobre off-site backup worker",
"coulobre-offsite-worker.service",
),
"apache": ("Apache", "apache2.service"), "apache": ("Apache", "apache2.service"),
"php-fpm": ("PHP-FPM", f"{DEFAULT_PHP_RUNTIME.service}.service"), "php-fpm": ("PHP-FPM", f"{DEFAULT_PHP_RUNTIME.service}.service"),
"mariadb": ("MariaDB", "mariadb.service"), "mariadb": ("MariaDB", "mariadb.service"),