Compare commits

...
6 Commits
Author SHA1 Message Date
parkel 48905caec8 Merge pull request 'Prepare Coulobre Core 1.4.0' (#267) from release/core-1.4.0 into main
Coulobre Panel CI / Checks (Python 3.12) (push) Successful in 1m46s
Coulobre Panel CI / Checks (Python 3.14) (push) Successful in 1m58s
Publish release to APT / publish (release) Successful in 3s
Reviewed-on: #267
2026-12-03 21:55:54 +01:00
parkel f02f907ca1 Prepare Coulobre Core 1.4.0
Coulobre Panel CI / Checks (Python 3.12) (pull_request) Successful in 1m46s
Coulobre Panel CI / Checks (Python 3.14) (pull_request) Successful in 1m57s
2026-12-03 21:45:23 +01:00
parkel acfed5bdfa Merge pull request 'Support manual off-site backups and verified archive recovery' (#265) from feature/offsite-backup-workflows into main
Coulobre Panel CI / Checks (Python 3.12) (push) Successful in 1m45s
Coulobre Panel CI / Checks (Python 3.14) (push) Successful in 1m57s
Reviewed-on: #265
2026-12-03 21:17:45 +01:00
parkel ecded4f123 Use local off-site destinations for manual backups and recovery
Coulobre Panel CI / Checks (Python 3.12) (pull_request) Successful in 1m46s
Coulobre Panel CI / Checks (Python 3.14) (pull_request) Successful in 1m58s
2026-12-03 21:14:02 +01:00
parkel 59ccb95594 Merge pull request 'Exclude generated Python bytecode from source releases' (#263) from fix/exclude-bytecode-from-source-release into main
Coulobre Panel CI / Checks (Python 3.12) (push) Successful in 1m56s
Coulobre Panel CI / Checks (Python 3.14) (push) Successful in 1m58s
Reviewed-on: #263
2026-12-03 20:49:48 +01:00
parkel 5cca093ea0 Exclude generated bytecode from source releases
Coulobre Panel CI / Checks (Python 3.12) (pull_request) Successful in 1m46s
Coulobre Panel CI / Checks (Python 3.14) (pull_request) Successful in 1m58s
2026-12-03 20:44:01 +01:00
23 changed files with 809 additions and 39 deletions

No files matched your search

+2
View File
@@ -62,6 +62,8 @@ jobs:
if: matrix.python-version == '3.14'
run: |
python -m pip install build
# Exercise source packaging with generated installer bytecode present.
python -m compileall -q deploy/panel_installer
python -m build
python tools/check_core_release.py dist/*.tar.gz dist/*.whl
python tools/build_deb.py dist/*.tar.gz dist/*.whl
+1
View File
@@ -2,3 +2,4 @@ include CONTRIBUTING.md manage.py
graft deploy
graft docs
graft tests
global-exclude *.pyc *.pyo
@@ -20,4 +20,5 @@ PrivateTmp=true
PrivateDevices=true
ProtectHome=true
ProtectSystem=strict
ReadWritePaths=-/var/lib/coulobre/account-backups
RestrictAddressFamilies=AF_UNIX AF_INET AF_INET6
+30 -9
View File
@@ -1982,7 +1982,7 @@ worker delivery from recreating an expired archive.
#### Copy scheduled account backups off-site
Coulobre can send scheduled archives to an encrypted restic repository over
Coulobre can send account 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)
@@ -2028,6 +2028,15 @@ For manual installations or additional destinations, set
`/etc/coulobre/panel.env`. This setting contains IDs and labels. Each ID
maps to a directory under `/etc/coulobre/offsite` on the backup node.
Local tooling can also publish an ID-to-label JSON object in
`/etc/coulobre-offsite-destinations.json`. Use a root-owned regular file
with mode `0644` and replace it atomically. Add an ID only after preparing
and verifying its root-only profile. The catalog contains no hostnames,
repository paths or credentials. Existing IDs from `panel.env` take
precedence. The panel and workers discover updates without a restart once
the off-site services are installed and running. Never repoint an existing
ID to a different repository.
```sh
sudo groupadd --system coulobre-offsite-requests
sudo useradd --system --user-group --no-create-home --home-dir /nonexistent \
@@ -2041,16 +2050,18 @@ 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
Choose the destination in **Backup schedule** for future scheduled backups,
or next to **Create backup** to send a one-off copy. Both use the same local
archive and transfer queue. 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.
failed copy from the archive history or include a destination in a manual
backup. 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
@@ -2059,10 +2070,20 @@ 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.
On the backup archive list, **Recover local archive** downloads a verified
copy and checks it against the snapshot ID and SHA-256 recorded by the panel.
The recovered copy appears as a separate local archive. It does not change
live content, revive expired archives or inherit the source's retention
schedule. Use the existing website, database or mailbox restore actions on
the recovered archive, subject to the same restore permissions and target
checks. On a manual upgrade, update the installed off-site socket service
unit from the release along with the panel, so recovery can write to the
local account backup directory.
To recover without the panel, take the destination ID, account ID and backup
ID from the archive history. On a node with the destination profile, the
recovery command 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
+1 -1
View File
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
[project]
name = "coulobre-panel"
version = "1.3.1"
version = "1.4.0"
description = "A web hosting control panel for hosting providers and resellers."
readme = "README.md"
requires-python = ">=3.12"
+2 -2
View File
@@ -1,7 +1,6 @@
from uuid import uuid4
from django import forms
from django.conf import settings
from django.core.exceptions import ValidationError
from coulobre.account_backup_retention import MAX_RETAINED_BACKUPS
@@ -13,6 +12,7 @@ from coulobre.database_node import DatabaseSpec
from .installation_features import panel_feature_allowed
from .models import AccountBackupSchedule
from .offsite_destinations import offsite_destinations
SCHEDULE_FIELDS = (
"enabled",
@@ -51,7 +51,7 @@ class AccountBackupScheduleForm(forms.Form):
if not allow_mail and not self.initial.get("include_mailboxes"):
del self.fields["include_mailboxes"]
destinations = (
settings.OFFSITE_BACKUP_DESTINATIONS
offsite_destinations()
if panel_feature_allowed("OFFSITE_BACKUP_DESTINATIONS")
else {}
)
+10 -2
View File
@@ -15,6 +15,7 @@ from .models import (
HostingMailbox,
OffsiteBackupTransfer,
)
from .offsite_destinations import offsite_destinations
from .resource_requests import lock_hosting_account, require_open_account
@@ -68,9 +69,15 @@ def queue_account_backup(
include_website=True,
include_databases=True,
database_suffix="",
offsite_destination="",
):
account = lock_hosting_account(account_id, customer_id=customer_id)
require_open_account(account)
if offsite_destination and (
customer_id is not None
or offsite_destination not in offsite_destinations()
):
raise ValidationError("Choose an available off-site destination.")
if database_suffix and not (
customer_id is not None
and include_databases
@@ -92,6 +99,7 @@ def queue_account_backup(
include_databases=include_databases,
export_customer_id=customer_id,
database_suffix=database_suffix,
offsite_destination=offsite_destination,
)
@@ -121,7 +129,7 @@ def _enqueue_backup(
export_customer_id=export_customer_id,
export_database_suffix=database_suffix,
)
if scheduled_for is not None and offsite_destination:
if offsite_destination:
OffsiteBackupTransfer.objects.create(
backup=job, destination=offsite_destination
)
@@ -157,7 +165,7 @@ def save_backup_schedule(account_id, *, can_manage_mail, schedule_fields):
if (
schedule_fields["enabled"]
and destination
and destination not in settings.OFFSITE_BACKUP_DESTINATIONS
and destination not in offsite_destinations()
):
raise ValidationError("Choose an available off-site destination.")
@@ -9,6 +9,7 @@ from coulobre.linked_updates import UNIT_DIR
from .dns_defaults import zone_defaults
from .models import PanelFeaturePolicy
from .offsite_destinations import offsite_destinations
DEPLOYMENT_GUIDE = (
"https://code.hosting.hippogrief.nl/hippogrief/coulobre/"
@@ -32,6 +33,8 @@ class Feature:
@property
def configured(self):
if self.setting == "OFFSITE_BACKUP_DESTINATIONS":
return bool(offsite_destinations())
if self.setting == "DEFAULT_DNS_ZONES":
defaults = zone_defaults()
return bool(
@@ -224,7 +227,12 @@ current_policy = ContextVar("current_feature_policy", default=None)
def panel_feature_allowed(setting):
if not getattr(settings, setting):
configured = (
offsite_destinations()
if setting == "OFFSITE_BACKUP_DESTINATIONS"
else getattr(settings, setting)
)
if not configured:
return False
return not panel_feature_paused(setting)
+7 -1
View File
@@ -32,6 +32,7 @@ from .models import (
PanelFeaturePolicy,
WebsiteDomain,
)
from .offsite_destinations import offsite_destinations
from .operator_tools import package_operation_pending, queue_operator_request
from .update_views import inspect_linked_nodes
@@ -55,10 +56,15 @@ TOOL_SETTINGS = {
def managed_tool_available(tool):
_, setting, prerequisite = TOOL_FEATURES[tool]
configured = (
offsite_destinations()
if tool == "offsite"
else getattr(settings, setting)
)
return (
Path(SOCKET).is_socket()
and PACKAGE_ASSETS.is_dir()
and not getattr(settings, setting)
and not configured
and getattr(settings, prerequisite)
)
@@ -0,0 +1,72 @@
# Generated by Django 5.2.19 on 2026-12-03 20:08
import uuid
import django.db.models.deletion
import django.utils.timezone
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("hosting", "0092_independent_website_starter_page"),
]
operations = [
migrations.CreateModel(
name="OffsiteBackupRecovery",
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)),
(
"recovered_id",
models.UUIDField(
default=uuid.uuid4, editable=False, unique=True
),
),
(
"recovered_backup",
models.OneToOneField(
null=True,
on_delete=django.db.models.deletion.SET_NULL,
related_name="offsite_recovery",
to="hosting.accountbackupjob",
),
),
(
"transfer",
models.OneToOneField(
on_delete=django.db.models.deletion.CASCADE,
related_name="recovery",
to="hosting.offsitebackuptransfer",
),
),
],
options={
"indexes": [
models.Index(
fields=["finished_at", "requested_at"],
name="hosting_off_finishe_238a8b_idx",
)
],
},
),
]
+27 -4
View File
@@ -48,6 +48,7 @@ from coulobre.web_node import MAX_STORAGE_LIMIT_MIB, WebSite
from coulobre.website_job import MAX_JOB_COMMAND_LENGTH
from .fields import DomainNameField
from .offsite_destinations import offsite_destinations
class Reseller(models.Model):
@@ -1467,7 +1468,7 @@ class OffsiteBackupTransfer(ProvisioningJob):
return "Waiting for local archive"
if self.backup.problem:
return "Local backup failed"
if self.destination not in settings.OFFSITE_BACKUP_DESTINATIONS:
if not self.destination_available:
return "Destination unavailable"
if self.finished_at is not None:
return "Failed"
@@ -1477,11 +1478,33 @@ class OffsiteBackupTransfer(ProvisioningJob):
return "Retry scheduled"
return "Queued"
@property
def destination_available(self):
return self.destination in offsite_destinations()
@property
def label(self):
return settings.OFFSITE_BACKUP_DESTINATIONS.get(
self.destination, self.destination
)
return offsite_destinations().get(self.destination, self.destination)
class OffsiteBackupRecovery(ProvisioningJob):
transfer = models.OneToOneField(
OffsiteBackupTransfer,
on_delete=models.CASCADE,
related_name="recovery",
)
recovered_id = models.UUIDField(
default=uuid.uuid4, unique=True, editable=False
)
recovered_backup = models.OneToOneField(
AccountBackupJob,
on_delete=models.SET_NULL,
null=True,
related_name="offsite_recovery",
)
class Meta:
indexes = [models.Index(fields=("finished_at", "requested_at"))]
class AccountBackupExpiration(ProvisioningJob):
+76 -4
View File
@@ -1,6 +1,5 @@
from datetime import timedelta
from django.conf import settings
from django.core.exceptions import ValidationError
from django.db import transaction
from django.db.models import F, Q
@@ -11,11 +10,17 @@ from coulobre.offsite_backup import (
OFFSITE_SOCKET,
TRANSFER_TIMEOUT_SECONDS,
OffsiteBackupRequest,
OffsiteRecoveryRequest,
)
from .models import OffsiteBackupTransfer
from .models import (
AccountBackupJob,
OffsiteBackupRecovery,
OffsiteBackupTransfer,
)
from .node_client import apply_on_local_node
from .notifications import notify_backup
from .offsite_destinations import offsite_destinations
OFFSITE_BACKUP_QUEUE = "coulobre-offsite-backups"
OFFSITE_BACKUP_LEASE = timedelta(seconds=TRANSFER_TIMEOUT_SECONDS + 60)
@@ -28,7 +33,7 @@ TRANSFER_PROBLEM = (
def transfer_scope(now):
return {
"next_attempt_at__lte": now,
"destination__in": settings.OFFSITE_BACKUP_DESTINATIONS,
"destination__in": offsite_destinations(),
"backup__finished_at__isnull": False,
"backup__problem": "",
"backup__expired_at__isnull": True,
@@ -130,7 +135,7 @@ def run_offsite_transfer(job_id):
@transaction.atomic
def retry_offsite_transfer(transfer):
if transfer.destination not in settings.OFFSITE_BACKUP_DESTINATIONS:
if transfer.destination not in offsite_destinations():
raise ValidationError(
"Configure the original off-site destination before retrying."
)
@@ -144,3 +149,70 @@ def retry_offsite_transfer(transfer):
next_attempt_at=timezone.now(),
):
raise ValidationError("Only failed off-site transfers can be retried.")
@transaction.atomic
def queue_offsite_recovery(transfer):
transfer = OffsiteBackupTransfer.objects.select_for_update().get(
pk=transfer.pk
)
if (
transfer.verified_at is None
or transfer.destination not in offsite_destinations()
):
raise ValidationError("Choose an available, verified off-site copy.")
job, created = OffsiteBackupRecovery.objects.get_or_create(
transfer=transfer
)
if not created and job.problem:
OffsiteBackupRecovery.objects.requeue(
OffsiteBackupRecovery.objects.filter(pk=job.pk).exclude(problem="")
)
def recover_verified_backup(job):
transfer = job.transfer
source = transfer.backup
if (
transfer.verified_at is None
or transfer.destination not in offsite_destinations()
):
raise ValueError("The verified off-site copy is unavailable.")
request = OffsiteRecoveryRequest(
OffsiteBackupRequest(
source.account_id, source.backup_id, transfer.destination
),
job.recovered_id,
transfer.snapshot,
transfer.sha256,
source.archive_bytes,
)
reply = apply_on_local_node(
request,
OFFSITE_SOCKET,
"off-site backup node",
"archive recovery",
timeout=TRANSFER_TIMEOUT_SECONDS + 20,
)
size = reply.get("archive_bytes")
if (
type(size) is not int
or not 1 <= size < 2**63
or (source.archive_bytes is not None and size != source.archive_bytes)
):
raise ValueError("The off-site node returned an invalid archive size.")
archive, _ = AccountBackupJob.objects.get_or_create(
backup_id=job.recovered_id,
defaults={
"account": source.account,
"manifest": source.manifest,
"archive_bytes": size,
"finished_at": timezone.now(),
},
)
if (
archive.account_id != source.account_id
or archive.manifest != source.manifest
):
raise ValueError("The recovered archive does not match the backup.")
return {"recovered_backup_id": archive.pk}
@@ -0,0 +1,39 @@
"""Discover local off-site profiles without reading credentials."""
import json
import os
import stat
from pathlib import Path
from django.conf import settings
from coulobre.offsite_backup import destination_labels
CATALOG = Path("/etc/coulobre-offsite-destinations.json")
MAX_CATALOG_BYTES = 16 * 1024
def catalog_labels():
try:
descriptor = os.open(
CATALOG, os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK
)
with os.fdopen(descriptor, "rb") as stream:
info = os.fstat(stream.fileno())
if (
not stat.S_ISREG(info.st_mode)
or info.st_uid != 0
or info.st_mode & 0o022
):
return {}
content = stream.read(MAX_CATALOG_BYTES + 1)
if len(content) <= MAX_CATALOG_BYTES:
return destination_labels(json.loads(content))
except (OSError, ValueError, RecursionError):
pass
return {}
def offsite_destinations():
# Never rebind or relabel an existing statically configured ID.
return catalog_labels() | settings.OFFSITE_BACKUP_DESTINATIONS
+23 -2
View File
@@ -60,6 +60,7 @@ from .models import (
MailFilterCheck,
MailRoutingPublication,
MailVacationPublication,
OffsiteBackupRecovery,
OffsiteBackupTransfer,
SignInWindow,
SitePhpSettings,
@@ -112,9 +113,11 @@ from .offsite_backups import (
OFFSITE_BACKUP_LEASE,
OFFSITE_BACKUP_QUEUE,
finish_interrupted_transfers,
recover_verified_backup,
run_offsite_transfer,
transfer_scope,
)
from .offsite_destinations import offsite_destinations
from .password_reset import send_customer_reset_email
from .php_settings import plan_php_versions
from .resource_requests import lock_hosting_account
@@ -500,7 +503,7 @@ def plan_account_backup_expirations():
@shared_task
def dispatch_offsite_backups():
if settings.LOCAL_ACCOUNT_BACKUPS and settings.OFFSITE_BACKUP_DESTINATIONS:
if settings.LOCAL_ACCOUNT_BACKUPS and offsite_destinations():
now = timezone.now()
finish_interrupted_transfers(now)
dispatch_provisioning_jobs(
@@ -511,14 +514,32 @@ def dispatch_offsite_backups():
attempts__lt=MAX_OFFSITE_ATTEMPTS,
**transfer_scope(now),
)
dispatch_provisioning_jobs(
OffsiteBackupRecovery,
recover_offsite_backup,
OFFSITE_BACKUP_QUEUE,
lease=OFFSITE_BACKUP_LEASE,
)
@shared_task(acks_late=True, reject_on_worker_lost=True)
def transfer_offsite_backup(job_id):
if settings.LOCAL_ACCOUNT_BACKUPS and settings.OFFSITE_BACKUP_DESTINATIONS:
if settings.LOCAL_ACCOUNT_BACKUPS and offsite_destinations():
run_offsite_transfer(job_id)
@shared_task(acks_late=True, reject_on_worker_lost=True)
def recover_offsite_backup(job_id):
if settings.LOCAL_ACCOUNT_BACKUPS:
run_provisioning_job(
OffsiteBackupRecovery.objects.select_related("transfer__backup"),
job_id,
recover_verified_backup,
"The backup node did not confirm recovery. You can retry.",
lease=OFFSITE_BACKUP_LEASE,
)
def dispatch_provisioning_jobs(
model, task, queue, *, lease=REDISPATCH_AFTER, condition=None, **scope
):
@@ -11,6 +11,8 @@
<td>
{% if job.scheduled_for %}
Scheduled <time datetime="{{ job.scheduled_for|date:"c" }}">{{ job.scheduled_for|date:"j M Y, H:i" }} UTC</time>
{% elif job.offsite_recovery %}
Recovered from off-site
{% else %}
Manual
{% endif %}
@@ -39,6 +41,25 @@
<div>Account ID <code>{{ job.account_id }}</code></div>
<div>Destination ID <code>{{ transfer.destination }}</code></div>
</details>
{% with recovery=transfer.recovery %}
{% if recovery %}
{% if recovery.recovered_backup_id %}
<div>Recovered to a new local archive.</div>
{% elif recovery.problem %}
<div>{{ recovery.problem }}</div>
{% else %}
<div>Recovery {{ recovery.state }}.</div>
{% endif %}
{% endif %}
{% if can_retry_offsite and transfer.destination_available %}
{% if not recovery or recovery.problem %}
<form method="post" action="{% url 'panel:recover_offsite_backup' account.pk job.pk %}">
{% csrf_token %}
<button type="submit" class="button secondary">{% if recovery.problem %}Retry recovery{% else %}Recover local archive{% endif %}</button>
</form>
{% endif %}
{% endif %}
{% endwith %}
{% elif transfer.problem %}
<div>{{ transfer.problem }}</div>
{% if can_retry_offsite and transfer.status == "Failed" %}
@@ -22,6 +22,15 @@
{% if account_backup_allow_mail %}
<label><input type="checkbox" name="include_mail" value="1"> Include mailboxes</label>
{% endif %}
{% if backup_destinations %}
<label for="manual-backup-destination">Destination</label>
<select id="manual-backup-destination" name="offsite_destination">
<option value="">Local archive only</option>
{% for id, label in backup_destinations.items %}
<option value="{{ id }}">{{ label }}</option>
{% endfor %}
</select>
{% endif %}
<button class="button primary" type="submit">Create backup</button>
</form>
{% endif %}
+201 -4
View File
@@ -1,6 +1,9 @@
import json
import os
from datetime import timedelta
from pathlib import Path
from tempfile import TemporaryDirectory
from types import SimpleNamespace
from unittest.mock import patch
from uuid import uuid4
@@ -11,19 +14,35 @@ 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.offsite_backup import (
OffsiteBackupRequest,
OffsiteRecoveryRequest,
destination_labels,
)
from coulobre.offsite_node import (
OffsiteRepositoryError,
Repository,
recover_offsite_backup,
)
from coulobre.web_node import WebSite
from . import offsite_destinations as catalog
from .account_backups import queue_account_backup, queue_due_account_backups
from .backup_retention import plan_backup_expirations
from .models import (
AccountBackupExpiration,
HostingAccount,
OffsiteBackupRecovery,
OffsiteBackupTransfer,
)
from .offsite_backups import MAX_ATTEMPTS, OFFSITE_BACKUP_QUEUE
from .tasks import dispatch_offsite_backups, transfer_offsite_backup
from .tasks import (
dispatch_offsite_backups,
transfer_offsite_backup,
)
from .tasks import (
recover_offsite_backup as run_recovery,
)
class OffsiteRepositoryTests(SimpleTestCase):
@@ -68,6 +87,73 @@ class OffsiteRepositoryTests(SimpleTestCase):
):
repository.snapshot(request)
def test_recovery_rejects_replaced_snapshot_before_downloading(self):
source = OffsiteBackupRequest(42, uuid4(), "vault")
request = OffsiteRecoveryRequest(
source, uuid4(), "a" * 64, "b" * 64, 4096
)
self.assertEqual(
OffsiteRecoveryRequest.from_manifest(request.manifest()), request
)
with (
patch.object(Repository, "for_destination"),
patch.object(
Repository, "snapshot", return_value=("c" * 64, "b" * 64)
),
patch.object(Repository, "read_archive") as download,
):
repository = Repository(Path("/etc/coulobre/offsite/vault"))
Repository.for_destination.return_value = repository
with self.assertRaisesMessage(ValueError, "differs from"):
recover_offsite_backup(
source,
Path("unused.zip"),
expected_snapshot=(request.snapshot, request.sha256),
expected_size=request.size,
)
download.assert_not_called()
class OffsiteCatalogTests(SimpleTestCase):
@override_settings(OFFSITE_BACKUP_DESTINATIONS={"vault": "Existing"})
def test_reload_and_ignore_unsafe_catalog(self):
with TemporaryDirectory() as temporary:
path = Path(temporary) / "destinations.json"
original_fstat = os.fstat
def root_file(fd):
info = original_fstat(fd)
return SimpleNamespace(st_uid=0, st_mode=info.st_mode)
with (
patch.object(catalog, "CATALOG", path),
patch.object(os, "fstat", side_effect=root_file),
):
self.assertEqual(
catalog.offsite_destinations(), {"vault": "Existing"}
)
path.write_text('{"vault":"Ignored","managed":"Managed"}')
path.chmod(0o644)
self.assertEqual(
catalog.offsite_destinations(),
{"vault": "Existing", "managed": "Managed"},
)
path.chmod(0o666)
self.assertEqual(
catalog.offsite_destinations(), {"vault": "Existing"}
)
path.chmod(0o644)
path.write_text('{"../untrusted":"Invalid"}')
self.assertEqual(
catalog.offsite_destinations(), {"vault": "Existing"}
)
path.unlink()
path.symlink_to(Path(temporary) / "other.json")
path.with_name("other.json").write_text('{"foreign":"Unsafe"}')
self.assertEqual(
catalog.offsite_destinations(), {"vault": "Existing"}
)
@override_settings(
LOCAL_ACCOUNT_BACKUPS=True,
@@ -119,7 +205,7 @@ class OffsiteBackupWorkflowTests(TestCase):
**values,
)
def test_only_scheduled_backups_capture_the_configured_destination(self):
def test_schedules_capture_the_configured_destination(self):
response = self.client.post(
self.schedule,
{
@@ -160,6 +246,117 @@ class OffsiteBackupWorkflowTests(TestCase):
"Select a valid choice",
)
@override_settings(OFFSITE_BACKUP_DESTINATIONS={})
def test_managed_destination_is_selectable_and_dispatched_without_restart(
self,
):
manual = reverse("panel:account_backup_create", args=[self.account.pk])
with patch.object(
catalog, "catalog_labels", return_value={"managed": "Vault"}
):
self.assertContains(self.client.get(self.schedule), "Vault")
self.assertContains(
self.client.get(self.account.get_absolute_url()),
'id="manual-backup-destination"',
)
self.assertEqual(
self.client.post(
manual, {"offsite_destination": "unknown"}
).status_code,
409,
)
self.assertRedirects(
self.client.post(manual, {"offsite_destination": "managed"}),
self.account.get_absolute_url(),
)
transfer = OffsiteBackupTransfer.objects.get()
self.assertEqual(transfer.destination, "managed")
self.assertIsNone(transfer.backup.scheduled_for)
self.assertEqual(transfer.status, "Waiting for local archive")
transfer.backup.finished_at = timezone.now()
transfer.backup.save(update_fields=["finished_at"])
with patch.object(
transfer_offsite_backup, "apply_async"
) as publish:
dispatch_offsite_backups.run()
publish.assert_called_once_with(
args=[transfer.pk], queue=OFFSITE_BACKUP_QUEUE, retry=False
)
@override_settings(LOCAL_WEBSITE_RESTORE=True)
def test_verified_copy_becomes_a_separate_restorable_archive(self):
source = self.archive(expired_at=self.now, archive_bytes=4096)
transfer = self.transfer(
source,
verified_at=self.now,
finished_at=self.now,
snapshot="a" * 64,
sha256="b" * 64,
)
recover = reverse(
"panel:recover_offsite_backup",
args=[self.account.pk, transfer.backup_id],
)
self.assertContains(
self.client.get(self.history), "Recover local archive"
)
for _ in range(2):
self.assertRedirects(self.client.post(recover), self.history)
job = OffsiteBackupRecovery.objects.get(transfer=transfer)
with patch.object(run_recovery, "apply_async") as publish:
dispatch_offsite_backups.run()
publish.assert_called_once_with(
args=[job.pk], queue=OFFSITE_BACKUP_QUEUE, retry=False
)
with patch(
"coulobre.hosting.offsite_backups.apply_on_local_node",
return_value={"archive_bytes": 4096},
) as restore:
run_recovery.run(job.pk)
run_recovery.run(job.pk)
restore.assert_called_once()
request = restore.call_args.args[0]
self.assertEqual(request.snapshot, transfer.snapshot)
self.assertEqual(request.sha256, transfer.sha256)
self.assertEqual(request.source.backup_id, source.backup_id)
job.refresh_from_db()
recovered = job.recovered_backup
self.assertTrue(recovered.archive_is_restorable)
self.assertEqual(recovered.manifest, source.manifest)
self.assertNotEqual(recovered.backup_id, source.backup_id)
self.assertIsNone(recovered.scheduled_for)
source.refresh_from_db()
self.assertEqual(source.expired_at, self.now)
self.assertContains(
self.client.get(self.history),
reverse(
"panel:website_restore", args=[self.account.pk, recovered.pk]
),
)
def test_recovery_requires_permission_a_verified_copy_and_matching_account(
self,
):
transfer = self.transfer()
recover = reverse(
"panel:recover_offsite_backup",
args=[self.account.pk, transfer.backup_id],
)
self.assertEqual(self.client.post(recover).status_code, 404)
transfer.verified_at = self.now
transfer.save(update_fields=["verified_at"])
other = HostingAccount.objects.create(
name="Other", primary_domain="other.test"
)
foreign = reverse(
"panel:recover_offsite_backup", args=[other.pk, transfer.backup_id]
)
self.assertEqual(self.client.post(foreign).status_code, 404)
user = get_user_model().objects.create_user("recovery-limited")
self.client.force_login(user)
self.assertEqual(self.client.post(recover).status_code, 403)
self.assertFalse(OffsiteBackupRecovery.objects.exists())
def test_only_finished_local_archives_are_dispatched(self):
ready = self.transfer()
self.transfer(self.archive(finished_at=None))
@@ -0,0 +1,122 @@
import os
from contextlib import nullcontext
from pathlib import Path
from tempfile import TemporaryDirectory
from unittest import skipUnless
from unittest.mock import patch
from uuid import uuid4
from django.test import SimpleTestCase
from coulobre import account_backup, account_backup_request, offsite_node
from coulobre import account_restore_request as restore
from coulobre import web_node_backup as web
from coulobre.offsite_backup import (
OffsiteBackupRequest,
OffsiteRecoveryRequest,
)
from coulobre.web_node import WebSite
SFTP_SERVER = Path("/usr/lib/openssh/sftp-server")
RESTIC = Path("/usr/bin/restic")
@skipUnless(
RESTIC.is_file() and SFTP_SERVER.is_file(),
"Install restic and openssh-sftp-server for the off-site round trip.",
)
class OffsiteRestoreRoundTripTests(SimpleTestCase):
def test_backup_transfer_recovery_and_native_file_restore(self):
root = Path(self.enterContext(TemporaryDirectory()))
archives, public, remote = (
root / name for name in ("archives", "public", "remote")
)
for directory in (archives, public, remote):
directory.mkdir(mode=0o700)
original = public / "index.html"
original.write_bytes(b"<h1>Before the backup</h1>")
original.chmod(0o640)
repository_file = root / "repository"
repository_file.write_text("sftp:coulobre-offsite:repository\n")
password_file = root / "password"
password_file.write_text("fixture password\n")
repository = offsite_node.Repository(root)
def direct_sftp(_repository, *args):
# Run OpenSSH's SFTP server over pipes without logging in.
return [
str(RESTIC),
"--no-cache",
"--repository-file",
str(repository_file),
"--password-file",
str(password_file),
"-o",
f"sftp.command={SFTP_SERVER} -d {remote}",
*args,
]
uid, gid = os.geteuid(), os.getegid()
self.enterContext(patch.object(os, "geteuid", return_value=0))
for module in (account_backup, web):
self.enterContext(patch.object(module, "require_root_directory"))
for module in (account_backup, offsite_node, web):
self.enterContext(patch.object(module, "check_root_file"))
self.enterContext(
patch.object(web, "locked_web_node", return_value=nullcontext())
)
self.enterContext(
patch.object(web, "site_storage", return_value=(public, uid, gid))
)
self.enterContext(
patch.object(account_backup_request, "BACKUP_DIRECTORY", archives)
)
self.enterContext(patch.object(restore, "RESTORE_DIRECTORY", root))
self.enterContext(
patch.object(
offsite_node,
"locked_root_directory",
return_value=nullcontext(),
)
)
self.enterContext(
patch.object(
offsite_node.Repository,
"for_destination",
return_value=repository,
)
)
self.enterContext(
patch.object(offsite_node.Repository, "arguments", direct_sftp)
)
repository.run("init")
site = WebSite(42, "fixture.example")
backup = OffsiteBackupRequest(42, uuid4(), "vault")
local = account_backup_request.backup_archive(42, backup.backup_id)
account_backup.create_backup(
account_backup.AccountBackup(site, ()), local, root / "unused.sock"
)
source_bytes = local.stat().st_size
copied = offsite_node.transfer_offsite_backup(backup)
self.assertEqual(offsite_node.transfer_offsite_backup(backup), copied)
local.unlink()
original.unlink()
recovery = OffsiteRecoveryRequest(
backup, uuid4(), copied["snapshot"], copied["sha256"], source_bytes
)
self.assertEqual(
offsite_node.recover_for_panel(recovery),
{"archive_bytes": source_bytes},
)
self.assertEqual(
offsite_node.recover_for_panel(recovery),
{"archive_bytes": source_bytes},
)
self.assertFalse(local.exists())
self.assertFalse(original.exists())
restore.restore_website_from_bundle(
restore.WebsiteRestoreRequest(
uuid4(), recovery.recovered_id, site, "index.html", False
)
)
self.assertEqual(original.read_bytes(), b"<h1>Before the backup</h1>")
+5
View File
@@ -576,6 +576,11 @@ urlpatterns = [
views.RetryOffsiteBackup.as_view(),
name="retry_offsite_backup",
),
path(
"accounts/<int:pk>/backups/<int:backup_pk>/offsite/recover/",
views.RecoverOffsiteBackup.as_view(),
name="recover_offsite_backup",
),
path(
"accounts/<int:pk>/backups/retention/",
views.EditBackupRetention.as_view(),
+41 -3
View File
@@ -126,7 +126,8 @@ from .models import (
WebsiteDomain,
WebsiteRestoreJob,
)
from .offsite_backups import retry_offsite_transfer
from .offsite_backups import queue_offsite_recovery, retry_offsite_transfer
from .offsite_destinations import offsite_destinations
from .php_settings import (
SitePhpSettingsForm,
last_applied_php_settings,
@@ -834,6 +835,8 @@ class AccountDetail(TenantScopeMixin, PermissionRequiredMixin, DetailView):
context["can_retry_offsite"] = panel_feature_allowed(
"OFFSITE_BACKUP_DESTINATIONS"
) and user.has_perms(RETRY_OFFSITE_BACKUP)
if context["can_retry_offsite"]:
context["backup_destinations"] = offsite_destinations()
context["manage_backup_retention"] = (
settings.LOCAL_BACKUP_RETENTION
and user.has_perms(MANAGE_BACKUP_RETENTION)
@@ -1422,6 +1425,16 @@ class RequestAccountBackup(OperatorOnlyMixin, PermissionRequiredMixin, View):
def post(self, request, pk):
if not panel_feature_allowed("LOCAL_ACCOUNT_BACKUPS"):
raise Http404
destination = request.POST.get("offsite_destination", "")
if destination:
if not request.user.has_perms(RETRY_OFFSITE_BACKUP):
return self.handle_no_permission()
if not panel_feature_allowed("OFFSITE_BACKUP_DESTINATIONS"):
return provisioning_conflict(
ValidationError(
"Off-site backup destinations are unavailable."
)
)
include_mailboxes = request.POST.get("include_mail") == "1"
if include_mailboxes:
if not mail_backups_enabled():
@@ -1429,7 +1442,11 @@ class RequestAccountBackup(OperatorOnlyMixin, PermissionRequiredMixin, View):
if not request.user.has_perm(VIEW_MAILBOXES):
return self.handle_no_permission()
try:
queue_account_backup(pk, include_mailboxes=include_mailboxes)
queue_account_backup(
pk,
include_mailboxes=include_mailboxes,
offsite_destination=destination,
)
except HostingAccount.DoesNotExist:
raise Http404 from None
except ValidationError as error:
@@ -1439,7 +1456,7 @@ class RequestAccountBackup(OperatorOnlyMixin, PermissionRequiredMixin, View):
def visible_account_backups(account, user):
backups = account.backup_jobs.select_related(
"expiration", "offsite_transfer"
"expiration", "offsite_transfer__recovery", "offsite_recovery"
).order_by("-requested_at", "-pk")
if not user.has_perm(VIEW_MAILBOXES):
backups = backups.exclude(manifest__has_key="mailboxes")
@@ -1512,6 +1529,27 @@ class RetryOffsiteBackup(OperatorOnlyMixin, PermissionRequiredMixin, View):
return redirect("panel:account_backup_archives", pk=pk)
class RecoverOffsiteBackup(OperatorOnlyMixin, PermissionRequiredMixin, View):
permission_required = RETRY_OFFSITE_BACKUP
def post(self, request, pk, backup_pk):
if not settings.LOCAL_ACCOUNT_BACKUPS or not panel_feature_allowed(
"OFFSITE_BACKUP_DESTINATIONS"
):
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__verified_at__isnull=False,
)
try:
queue_offsite_recovery(backup.offsite_transfer)
except ValidationError as error:
return provisioning_conflict(error)
return redirect("panel:account_backup_archives", pk=pk)
class BackupRetentionView(
OperatorOnlyMixin, PermissionRequiredMixin, FormView
):
+63
View File
@@ -80,3 +80,66 @@ class OffsiteBackupRequest:
@property
def archive_name(self):
return f"account-{self.account_id}-{self.backup_id}.zip"
@dataclass(frozen=True)
class OffsiteRecoveryRequest:
source: OffsiteBackupRequest
recovered_id: UUID
snapshot: str
sha256: str
size: int | None
def __post_init__(self):
if (
not isinstance(self.recovered_id, UUID)
or self.recovered_id == self.source.backup_id
or not all(
isinstance(value, str) and HEX_DIGEST.fullmatch(value)
for value in (self.snapshot, self.sha256)
)
or (
self.size is not None
and (type(self.size) is not int or not 1 <= self.size < 2**63)
)
):
raise ValueError("Expected the original off-site verification.")
@classmethod
def from_manifest(cls, data):
if (
not isinstance(data, dict)
or data.keys()
!= {
"version",
"source",
"recovered_id",
"snapshot",
"sha256",
"size",
}
or type(data["version"]) is not int
or data["version"] != 1
or not isinstance(data["recovered_id"], str)
):
raise ValueError("Expected a version 1 off-site recovery request.")
recovery_id = UUID(data["recovered_id"])
if str(recovery_id) != data["recovered_id"]:
raise ValueError("Expected a canonical recovery ID.")
return cls(
OffsiteBackupRequest.from_manifest(data["source"]),
recovery_id,
data["snapshot"],
data["sha256"],
data["size"],
)
def manifest(self):
return {
"version": 1,
"source": self.source.manifest(),
"recovered_id": str(self.recovered_id),
"snapshot": self.snapshot,
"sha256": self.sha256,
"size": self.size,
}
+46 -5
View File
@@ -10,7 +10,10 @@ from tempfile import NamedTemporaryFile
from zipfile import BadZipFile
from .account_backup import open_account_bundle, private_path
from .account_backup_request import backup_archive, expiration_marker
from .account_backup_request import (
backup_archive,
expiration_marker,
)
from .node_files import (
check_root_file,
locked_root_directory,
@@ -22,6 +25,7 @@ from .offsite_backup import (
HEX_DIGEST,
TRANSFER_TIMEOUT_SECONDS,
OffsiteBackupRequest,
OffsiteRecoveryRequest,
validate_destination,
)
@@ -230,16 +234,22 @@ def verify_destination(destination):
Repository.for_destination(destination).run("cat", "config")
def recover_offsite_backup(request, output):
def recover_offsite_backup(
request, output, *, expected_snapshot=None, expected_size=None
):
repository = Repository.for_destination(request.destination)
snapshot = repository.snapshot(request)
if snapshot is None:
raise ValueError("No off-site snapshot matches this backup ID.")
if expected_snapshot is not None and snapshot != expected_snapshot:
raise ValueError(
"The off-site snapshot differs from the verified copy."
)
output = private_path(output, new=True)
snapshot_id, digest = snapshot
with NamedTemporaryFile(dir=output.parent) as staged:
recovered = repository.read_archive(
request, snapshot_id, target=staged
request, snapshot_id, target=staged, expected_size=expected_size
)
if recovered != digest:
raise ValueError(
@@ -254,15 +264,46 @@ def recover_offsite_backup(request, output):
return snapshot_id
def recover_for_panel(request):
output = backup_archive(request.source.account_id, request.recovered_id)
with locked_root_directory(STATE):
if os.path.lexists(expiration_marker(output)):
raise ValueError("This recovery archive has expired.")
if os.path.lexists(output):
check_root_file(output, mode=0o600)
with output.open("rb") as source:
digest = hashlib.file_digest(source, "sha256").hexdigest()
if digest != request.sha256:
raise ValueError(
"A different recovery archive already exists."
)
else:
recover_offsite_backup(
request.source,
output,
expected_snapshot=(request.snapshot, request.sha256),
expected_size=request.size,
)
return {"archive_bytes": output.stat().st_size}
def parse_offsite_request(data):
if isinstance(data, dict) and "source" in data:
return OffsiteRecoveryRequest.from_manifest(data)
return OffsiteBackupRequest.from_manifest(data)
def serve_offsite_request():
def apply(request):
try:
if isinstance(request, OffsiteRecoveryRequest):
return recover_for_panel(request)
return transfer_offsite_backup(request)
except OSError:
except (BadZipFile, OSError):
raise ValueError(
"The backup node could not access the archive or destination."
) from None
return serve_apply_request(
1, OffsiteBackupRequest.from_manifest, apply, include_result=True
1, parse_offsite_request, apply, include_result=True
)
+1 -1
View File
@@ -519,7 +519,7 @@ if LOCAL_BACKUP_RETENTION:
"schedule": 300.0,
"options": {"expires": 295.0},
}
if LOCAL_ACCOUNT_BACKUPS and OFFSITE_BACKUP_DESTINATIONS:
if LOCAL_ACCOUNT_BACKUPS:
CELERY_BEAT_SCHEDULE["dispatch-offsite-backups"] = {
"task": "coulobre.hosting.tasks.dispatch_offsite_backups",
"schedule": 15.0,