Compare commits
11
Commits
9356bc8dd8
...
v1.4.0
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
48905caec8 | ||
|
|
f02f907ca1 | ||
|
|
acfed5bdfa | ||
|
|
ecded4f123 | ||
|
|
59ccb95594 | ||
|
|
5cca093ea0 | ||
|
|
708aeb92d9 | ||
|
|
a94129b499 | ||
|
|
2173ceef73 | ||
|
|
e74678af17 | ||
|
|
aab5634ff7 |
No files matched your search
@@ -62,6 +62,8 @@ jobs:
|
|||||||
if: matrix.python-version == '3.14'
|
if: matrix.python-version == '3.14'
|
||||||
run: |
|
run: |
|
||||||
python -m pip install build
|
python -m pip install build
|
||||||
|
# Exercise source packaging with generated installer bytecode present.
|
||||||
|
python -m compileall -q deploy/panel_installer
|
||||||
python -m build
|
python -m build
|
||||||
python tools/check_core_release.py dist/*.tar.gz dist/*.whl
|
python tools/check_core_release.py dist/*.tar.gz dist/*.whl
|
||||||
python tools/build_deb.py dist/*.tar.gz dist/*.whl
|
python tools/build_deb.py dist/*.tar.gz dist/*.whl
|
||||||
|
|||||||
+2
-8
@@ -194,14 +194,8 @@ python tools/web_update_manifest.py dist/coulobre_panel-0.10.2rc1-py3-none-any.w
|
|||||||
For example, “This zone changed before publication. Reload the account
|
For example, “This zone changed before publication. Reload the account
|
||||||
and try again.” Keep credentials and raw service output out of messages
|
and try again.” Keep credentials and raw service output out of messages
|
||||||
shown in the panel.
|
shown in the panel.
|
||||||
- Reuse existing templates and styles for controls, focus states, and
|
- Follow the [panel design guidelines](docs/panel-design.md) for Core and
|
||||||
status labels. Keep form inputs labelled and validation errors close to
|
Premium layouts, forms, and UI review.
|
||||||
the field that needs attention.
|
|
||||||
- Use the shared workspace template for signed-in pages. Place the page
|
|
||||||
heading first, followed by local tabs and any account, domain, or list
|
|
||||||
filters. Start the main content below the divider. Keep status updates
|
|
||||||
separate from forms the operator or customer may be editing.
|
|
||||||
[Workspace template](src/coulobre/hosting/templates/hosting/workspace_page.html)
|
|
||||||
|
|
||||||
## Checks
|
## Checks
|
||||||
|
|
||||||
|
|||||||
@@ -2,3 +2,4 @@ include CONTRIBUTING.md manage.py
|
|||||||
graft deploy
|
graft deploy
|
||||||
graft docs
|
graft docs
|
||||||
graft tests
|
graft tests
|
||||||
|
global-exclude *.pyc *.pyo
|
||||||
@@ -20,4 +20,5 @@ PrivateTmp=true
|
|||||||
PrivateDevices=true
|
PrivateDevices=true
|
||||||
ProtectHome=true
|
ProtectHome=true
|
||||||
ProtectSystem=strict
|
ProtectSystem=strict
|
||||||
|
ReadWritePaths=-/var/lib/coulobre/account-backups
|
||||||
RestrictAddressFamilies=AF_UNIX AF_INET AF_INET6
|
RestrictAddressFamilies=AF_UNIX AF_INET AF_INET6
|
||||||
+30
-9
@@ -1982,7 +1982,7 @@ worker delivery from recreating an expired archive.
|
|||||||
|
|
||||||
#### Copy scheduled account backups off-site
|
#### 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
|
SFTP. On the backup node, install restic and OpenSSH and create a directory
|
||||||
for each destination. This example uses the destination ID `vault`.
|
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)
|
[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
|
`/etc/coulobre/panel.env`. This setting contains IDs and labels. Each ID
|
||||||
maps to a directory under `/etc/coulobre/offsite` on the backup node.
|
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
|
```sh
|
||||||
sudo groupadd --system coulobre-offsite-requests
|
sudo groupadd --system coulobre-offsite-requests
|
||||||
sudo useradd --system --user-group --no-create-home --home-dir /nonexistent \
|
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
|
sudo systemctl restart coulobre-panel coulobre-worker coulobre-beat
|
||||||
```
|
```
|
||||||
|
|
||||||
Choose the destination in **Backup schedule**. The choice applies to future
|
Choose the destination in **Backup schedule** for future scheduled backups,
|
||||||
scheduled backups. The archive history shows transfer status. A copy becomes
|
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
|
**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
|
size and SHA-256 checksum. Allow time and bandwidth for both the upload
|
||||||
and verification within the 30-minute transfer deadline. An interrupted
|
and verification within the 30-minute transfer deadline. An interrupted
|
||||||
transfer reuses an existing snapshot with the same backup ID and verifies
|
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
|
it again. The worker makes up to five attempts before requiring a manual
|
||||||
retry. Operators with **Can change offsite backup transfer** can retry a
|
retry. Operators with **Can change offsite backup transfer** can retry a
|
||||||
failed copy from the archive history. Add `offsite-backups` to the local
|
failed copy from the archive history or include a destination in a manual
|
||||||
service health list to monitor the worker.
|
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
|
Archives awaiting verification stay on the backup node and do not count
|
||||||
toward the eligible local retention set. Once verified, they follow the
|
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
|
switching repositories. Keep the original profile and recovery credentials
|
||||||
for as long as you retain copies in that repository.
|
for as long as you retain copies in that repository.
|
||||||
|
|
||||||
To recover a copy, take its destination ID, account ID, and backup ID from
|
On the backup archive list, **Recover local archive** downloads a verified
|
||||||
the archive history. Run the recovery command on a node with the
|
copy and checks it against the snapshot ID and SHA-256 recorded by the panel.
|
||||||
destination profile. It looks up the snapshot by backup ID and verifies
|
The recovered copy appears as a separate local archive. It does not change
|
||||||
the checksum in its authenticated metadata before creating the output file.
|
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
|
```sh
|
||||||
sudo install -d -m 0700 /srv/coulobre-recovery
|
sudo install -d -m 0700 /srv/coulobre-recovery
|
||||||
|
|||||||
@@ -0,0 +1,72 @@
|
|||||||
|
# Panel design guidelines
|
||||||
|
|
||||||
|
Core and Premium share one panel interface. Core owns the workspace layout,
|
||||||
|
theme tokens, and reusable UI patterns. Both editions follow this guide.
|
||||||
|
Reuse Core's templates and classes before adding a new style. If a pattern
|
||||||
|
belongs in both editions, add it to Core and document it here. Premium should
|
||||||
|
only use shared components available in its supported Core versions.
|
||||||
|
|
||||||
|
## Page structure
|
||||||
|
|
||||||
|
- Extend [the workspace template][workspace] for signed-in pages. Follow
|
||||||
|
**HTTP Settings** for pages with tabs. Put the page title and any page-wide
|
||||||
|
actions first, then local tabs, then an account or domain selector if
|
||||||
|
needed. The workspace divider separates these controls from the content.
|
||||||
|
- Keep the page title stable across tabs. Mark the current tab with
|
||||||
|
`aria-current="page"` and give the tab navigation an accessible label.
|
||||||
|
- Use `.live-sections` to space stacked sections. Keep live status refreshes
|
||||||
|
separate from forms so they cannot erase edits or move keyboard focus.
|
||||||
|
- Use `.surface` for sections, `.section-heading` for ordinary section
|
||||||
|
headers, and `.table-scroll` around tables. Keep horizontal overflow in
|
||||||
|
the table wrapper and give empty or pending states an explicit label.
|
||||||
|
- Extensions may add their running software versions to **About Coulobre**
|
||||||
|
through the optional `panel_extension_versions` template context. Pass
|
||||||
|
pairs of plain-text labels and versions only after checking access to the
|
||||||
|
extension. Core does not load or inspect extension packages.
|
||||||
|
|
||||||
|
## Forms and actions
|
||||||
|
|
||||||
|
For a compact editor, use `.surface.editor-surface` on the card and
|
||||||
|
`.editor` on the form. Render Django fields with `form.as_div` so each
|
||||||
|
field, label, and validation message occupies one row in the shared grid.
|
||||||
|
Put the explanation and submit action inside the same grid. Don't add a
|
||||||
|
padded `.section-heading` inside an already padded editor card. The
|
||||||
|
heading, help, fields, and actions should share a left edge.
|
||||||
|
|
||||||
|
```django
|
||||||
|
<section class="surface editor-surface" aria-labelledby="example-heading">
|
||||||
|
<form method="post" class="editor">
|
||||||
|
{% csrf_token %}
|
||||||
|
<header>
|
||||||
|
<h2 id="example-heading">Edit settings</h2>
|
||||||
|
<p class="muted">Explain what these settings affect.</p>
|
||||||
|
</header>
|
||||||
|
{{ form.as_div }}
|
||||||
|
<div class="form-actions">
|
||||||
|
<button type="submit" class="button primary">Save settings</button>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
</section>
|
||||||
|
```
|
||||||
|
|
||||||
|
- Use one clear primary action per form. Put secondary actions such as
|
||||||
|
Cancel in the same `.form-actions` row when they apply to that form.
|
||||||
|
- Use short, sentence-case action labels. Keep field errors beside their
|
||||||
|
inputs. Use visible labels and keep essential instructions available
|
||||||
|
without relying on pointer hover.
|
||||||
|
- Prefer the shared compact type and spacing. Use [the panel stylesheet][css]
|
||||||
|
and its theme tokens for type, color, spacing, and focus states. Avoid
|
||||||
|
fixed control widths, inline styles, and page-specific font sizes.
|
||||||
|
|
||||||
|
## Review a UI change
|
||||||
|
|
||||||
|
Compare the result with a Core page that serves the same purpose. In light
|
||||||
|
and dark mode, check desktop and narrow widths, keyboard focus, and fields
|
||||||
|
with validation errors. Try long domains, identifiers, and filenames. Text
|
||||||
|
should stay readable, controls should remain inside their cards, and wide
|
||||||
|
tables should scroll within their wrapper. Verify empty and populated states
|
||||||
|
for lists. For Premium changes, use the same checks against the supported
|
||||||
|
Core layout before introducing a new pattern.
|
||||||
|
|
||||||
|
[workspace]: ../src/coulobre/hosting/templates/hosting/workspace_page.html
|
||||||
|
[css]: ../src/coulobre/hosting/static/hosting/panel.css
|
||||||
+1
-1
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
|
|||||||
|
|
||||||
[project]
|
[project]
|
||||||
name = "coulobre-panel"
|
name = "coulobre-panel"
|
||||||
version = "1.3.0"
|
version = "1.4.0"
|
||||||
description = "A web hosting control panel for hosting providers and resellers."
|
description = "A web hosting control panel for hosting providers and resellers."
|
||||||
readme = "README.md"
|
readme = "README.md"
|
||||||
requires-python = ">=3.12"
|
requires-python = ">=3.12"
|
||||||
|
|||||||
@@ -1,7 +1,6 @@
|
|||||||
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
|
||||||
@@ -13,6 +12,7 @@ from coulobre.database_node import DatabaseSpec
|
|||||||
|
|
||||||
from .installation_features import panel_feature_allowed
|
from .installation_features import panel_feature_allowed
|
||||||
from .models import AccountBackupSchedule
|
from .models import AccountBackupSchedule
|
||||||
|
from .offsite_destinations import offsite_destinations
|
||||||
|
|
||||||
SCHEDULE_FIELDS = (
|
SCHEDULE_FIELDS = (
|
||||||
"enabled",
|
"enabled",
|
||||||
@@ -51,7 +51,7 @@ class AccountBackupScheduleForm(forms.Form):
|
|||||||
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 = (
|
destinations = (
|
||||||
settings.OFFSITE_BACKUP_DESTINATIONS
|
offsite_destinations()
|
||||||
if panel_feature_allowed("OFFSITE_BACKUP_DESTINATIONS")
|
if panel_feature_allowed("OFFSITE_BACKUP_DESTINATIONS")
|
||||||
else {}
|
else {}
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -15,6 +15,7 @@ from .models import (
|
|||||||
HostingMailbox,
|
HostingMailbox,
|
||||||
OffsiteBackupTransfer,
|
OffsiteBackupTransfer,
|
||||||
)
|
)
|
||||||
|
from .offsite_destinations import offsite_destinations
|
||||||
from .resource_requests import lock_hosting_account, require_open_account
|
from .resource_requests import lock_hosting_account, require_open_account
|
||||||
|
|
||||||
|
|
||||||
@@ -68,9 +69,15 @@ def queue_account_backup(
|
|||||||
include_website=True,
|
include_website=True,
|
||||||
include_databases=True,
|
include_databases=True,
|
||||||
database_suffix="",
|
database_suffix="",
|
||||||
|
offsite_destination="",
|
||||||
):
|
):
|
||||||
account = lock_hosting_account(account_id, customer_id=customer_id)
|
account = lock_hosting_account(account_id, customer_id=customer_id)
|
||||||
require_open_account(account)
|
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 (
|
if database_suffix and not (
|
||||||
customer_id is not None
|
customer_id is not None
|
||||||
and include_databases
|
and include_databases
|
||||||
@@ -92,6 +99,7 @@ def queue_account_backup(
|
|||||||
include_databases=include_databases,
|
include_databases=include_databases,
|
||||||
export_customer_id=customer_id,
|
export_customer_id=customer_id,
|
||||||
database_suffix=database_suffix,
|
database_suffix=database_suffix,
|
||||||
|
offsite_destination=offsite_destination,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
@@ -121,7 +129,7 @@ def _enqueue_backup(
|
|||||||
export_customer_id=export_customer_id,
|
export_customer_id=export_customer_id,
|
||||||
export_database_suffix=database_suffix,
|
export_database_suffix=database_suffix,
|
||||||
)
|
)
|
||||||
if scheduled_for is not None and offsite_destination:
|
if offsite_destination:
|
||||||
OffsiteBackupTransfer.objects.create(
|
OffsiteBackupTransfer.objects.create(
|
||||||
backup=job, destination=offsite_destination
|
backup=job, destination=offsite_destination
|
||||||
)
|
)
|
||||||
@@ -157,7 +165,7 @@ def save_backup_schedule(account_id, *, can_manage_mail, schedule_fields):
|
|||||||
if (
|
if (
|
||||||
schedule_fields["enabled"]
|
schedule_fields["enabled"]
|
||||||
and destination
|
and destination
|
||||||
and destination not in settings.OFFSITE_BACKUP_DESTINATIONS
|
and destination not in offsite_destinations()
|
||||||
):
|
):
|
||||||
raise ValidationError("Choose an available off-site destination.")
|
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 .dns_defaults import zone_defaults
|
||||||
from .models import PanelFeaturePolicy
|
from .models import PanelFeaturePolicy
|
||||||
|
from .offsite_destinations import offsite_destinations
|
||||||
|
|
||||||
DEPLOYMENT_GUIDE = (
|
DEPLOYMENT_GUIDE = (
|
||||||
"https://code.hosting.hippogrief.nl/hippogrief/coulobre/"
|
"https://code.hosting.hippogrief.nl/hippogrief/coulobre/"
|
||||||
@@ -32,6 +33,8 @@ class Feature:
|
|||||||
|
|
||||||
@property
|
@property
|
||||||
def configured(self):
|
def configured(self):
|
||||||
|
if self.setting == "OFFSITE_BACKUP_DESTINATIONS":
|
||||||
|
return bool(offsite_destinations())
|
||||||
if self.setting == "DEFAULT_DNS_ZONES":
|
if self.setting == "DEFAULT_DNS_ZONES":
|
||||||
defaults = zone_defaults()
|
defaults = zone_defaults()
|
||||||
return bool(
|
return bool(
|
||||||
@@ -224,7 +227,12 @@ current_policy = ContextVar("current_feature_policy", default=None)
|
|||||||
|
|
||||||
|
|
||||||
def panel_feature_allowed(setting):
|
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 False
|
||||||
return not panel_feature_paused(setting)
|
return not panel_feature_paused(setting)
|
||||||
|
|
||||||
|
|||||||
@@ -32,6 +32,7 @@ from .models import (
|
|||||||
PanelFeaturePolicy,
|
PanelFeaturePolicy,
|
||||||
WebsiteDomain,
|
WebsiteDomain,
|
||||||
)
|
)
|
||||||
|
from .offsite_destinations import offsite_destinations
|
||||||
from .operator_tools import package_operation_pending, queue_operator_request
|
from .operator_tools import package_operation_pending, queue_operator_request
|
||||||
from .update_views import inspect_linked_nodes
|
from .update_views import inspect_linked_nodes
|
||||||
|
|
||||||
@@ -55,10 +56,15 @@ TOOL_SETTINGS = {
|
|||||||
|
|
||||||
def managed_tool_available(tool):
|
def managed_tool_available(tool):
|
||||||
_, setting, prerequisite = TOOL_FEATURES[tool]
|
_, setting, prerequisite = TOOL_FEATURES[tool]
|
||||||
|
configured = (
|
||||||
|
offsite_destinations()
|
||||||
|
if tool == "offsite"
|
||||||
|
else getattr(settings, setting)
|
||||||
|
)
|
||||||
return (
|
return (
|
||||||
Path(SOCKET).is_socket()
|
Path(SOCKET).is_socket()
|
||||||
and PACKAGE_ASSETS.is_dir()
|
and PACKAGE_ASSETS.is_dir()
|
||||||
and not getattr(settings, setting)
|
and not configured
|
||||||
and getattr(settings, prerequisite)
|
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",
|
||||||
|
)
|
||||||
|
],
|
||||||
|
},
|
||||||
|
),
|
||||||
|
]
|
||||||
@@ -48,6 +48,7 @@ from coulobre.web_node import MAX_STORAGE_LIMIT_MIB, WebSite
|
|||||||
from coulobre.website_job import MAX_JOB_COMMAND_LENGTH
|
from coulobre.website_job import MAX_JOB_COMMAND_LENGTH
|
||||||
|
|
||||||
from .fields import DomainNameField
|
from .fields import DomainNameField
|
||||||
|
from .offsite_destinations import offsite_destinations
|
||||||
|
|
||||||
|
|
||||||
class Reseller(models.Model):
|
class Reseller(models.Model):
|
||||||
@@ -1467,7 +1468,7 @@ class OffsiteBackupTransfer(ProvisioningJob):
|
|||||||
return "Waiting for local archive"
|
return "Waiting for local archive"
|
||||||
if self.backup.problem:
|
if self.backup.problem:
|
||||||
return "Local backup failed"
|
return "Local backup failed"
|
||||||
if self.destination not in settings.OFFSITE_BACKUP_DESTINATIONS:
|
if not self.destination_available:
|
||||||
return "Destination unavailable"
|
return "Destination unavailable"
|
||||||
if self.finished_at is not None:
|
if self.finished_at is not None:
|
||||||
return "Failed"
|
return "Failed"
|
||||||
@@ -1477,11 +1478,33 @@ class OffsiteBackupTransfer(ProvisioningJob):
|
|||||||
return "Retry scheduled"
|
return "Retry scheduled"
|
||||||
return "Queued"
|
return "Queued"
|
||||||
|
|
||||||
|
@property
|
||||||
|
def destination_available(self):
|
||||||
|
return self.destination in offsite_destinations()
|
||||||
|
|
||||||
@property
|
@property
|
||||||
def label(self):
|
def label(self):
|
||||||
return settings.OFFSITE_BACKUP_DESTINATIONS.get(
|
return offsite_destinations().get(self.destination, self.destination)
|
||||||
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):
|
class AccountBackupExpiration(ProvisioningJob):
|
||||||
|
|||||||
@@ -1,6 +1,5 @@
|
|||||||
from datetime import timedelta
|
from datetime import timedelta
|
||||||
|
|
||||||
from django.conf import settings
|
|
||||||
from django.core.exceptions import ValidationError
|
from django.core.exceptions import ValidationError
|
||||||
from django.db import transaction
|
from django.db import transaction
|
||||||
from django.db.models import F, Q
|
from django.db.models import F, Q
|
||||||
@@ -11,11 +10,17 @@ from coulobre.offsite_backup import (
|
|||||||
OFFSITE_SOCKET,
|
OFFSITE_SOCKET,
|
||||||
TRANSFER_TIMEOUT_SECONDS,
|
TRANSFER_TIMEOUT_SECONDS,
|
||||||
OffsiteBackupRequest,
|
OffsiteBackupRequest,
|
||||||
|
OffsiteRecoveryRequest,
|
||||||
)
|
)
|
||||||
|
|
||||||
from .models import OffsiteBackupTransfer
|
from .models import (
|
||||||
|
AccountBackupJob,
|
||||||
|
OffsiteBackupRecovery,
|
||||||
|
OffsiteBackupTransfer,
|
||||||
|
)
|
||||||
from .node_client import apply_on_local_node
|
from .node_client import apply_on_local_node
|
||||||
from .notifications import notify_backup
|
from .notifications import notify_backup
|
||||||
|
from .offsite_destinations import offsite_destinations
|
||||||
|
|
||||||
OFFSITE_BACKUP_QUEUE = "coulobre-offsite-backups"
|
OFFSITE_BACKUP_QUEUE = "coulobre-offsite-backups"
|
||||||
OFFSITE_BACKUP_LEASE = timedelta(seconds=TRANSFER_TIMEOUT_SECONDS + 60)
|
OFFSITE_BACKUP_LEASE = timedelta(seconds=TRANSFER_TIMEOUT_SECONDS + 60)
|
||||||
@@ -28,7 +33,7 @@ TRANSFER_PROBLEM = (
|
|||||||
def transfer_scope(now):
|
def transfer_scope(now):
|
||||||
return {
|
return {
|
||||||
"next_attempt_at__lte": now,
|
"next_attempt_at__lte": now,
|
||||||
"destination__in": settings.OFFSITE_BACKUP_DESTINATIONS,
|
"destination__in": offsite_destinations(),
|
||||||
"backup__finished_at__isnull": False,
|
"backup__finished_at__isnull": False,
|
||||||
"backup__problem": "",
|
"backup__problem": "",
|
||||||
"backup__expired_at__isnull": True,
|
"backup__expired_at__isnull": True,
|
||||||
@@ -130,7 +135,7 @@ def run_offsite_transfer(job_id):
|
|||||||
|
|
||||||
@transaction.atomic
|
@transaction.atomic
|
||||||
def retry_offsite_transfer(transfer):
|
def retry_offsite_transfer(transfer):
|
||||||
if transfer.destination not in settings.OFFSITE_BACKUP_DESTINATIONS:
|
if transfer.destination not in offsite_destinations():
|
||||||
raise ValidationError(
|
raise ValidationError(
|
||||||
"Configure the original off-site destination before retrying."
|
"Configure the original off-site destination before retrying."
|
||||||
)
|
)
|
||||||
@@ -144,3 +149,70 @@ def retry_offsite_transfer(transfer):
|
|||||||
next_attempt_at=timezone.now(),
|
next_attempt_at=timezone.now(),
|
||||||
):
|
):
|
||||||
raise ValidationError("Only failed off-site transfers can be retried.")
|
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
|
||||||
@@ -60,6 +60,7 @@ from .models import (
|
|||||||
MailFilterCheck,
|
MailFilterCheck,
|
||||||
MailRoutingPublication,
|
MailRoutingPublication,
|
||||||
MailVacationPublication,
|
MailVacationPublication,
|
||||||
|
OffsiteBackupRecovery,
|
||||||
OffsiteBackupTransfer,
|
OffsiteBackupTransfer,
|
||||||
SignInWindow,
|
SignInWindow,
|
||||||
SitePhpSettings,
|
SitePhpSettings,
|
||||||
@@ -112,9 +113,11 @@ from .offsite_backups import (
|
|||||||
OFFSITE_BACKUP_LEASE,
|
OFFSITE_BACKUP_LEASE,
|
||||||
OFFSITE_BACKUP_QUEUE,
|
OFFSITE_BACKUP_QUEUE,
|
||||||
finish_interrupted_transfers,
|
finish_interrupted_transfers,
|
||||||
|
recover_verified_backup,
|
||||||
run_offsite_transfer,
|
run_offsite_transfer,
|
||||||
transfer_scope,
|
transfer_scope,
|
||||||
)
|
)
|
||||||
|
from .offsite_destinations import offsite_destinations
|
||||||
from .password_reset import send_customer_reset_email
|
from .password_reset import send_customer_reset_email
|
||||||
from .php_settings import plan_php_versions
|
from .php_settings import plan_php_versions
|
||||||
from .resource_requests import lock_hosting_account
|
from .resource_requests import lock_hosting_account
|
||||||
@@ -500,7 +503,7 @@ def plan_account_backup_expirations():
|
|||||||
|
|
||||||
@shared_task
|
@shared_task
|
||||||
def dispatch_offsite_backups():
|
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()
|
now = timezone.now()
|
||||||
finish_interrupted_transfers(now)
|
finish_interrupted_transfers(now)
|
||||||
dispatch_provisioning_jobs(
|
dispatch_provisioning_jobs(
|
||||||
@@ -511,14 +514,32 @@ def dispatch_offsite_backups():
|
|||||||
attempts__lt=MAX_OFFSITE_ATTEMPTS,
|
attempts__lt=MAX_OFFSITE_ATTEMPTS,
|
||||||
**transfer_scope(now),
|
**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)
|
@shared_task(acks_late=True, reject_on_worker_lost=True)
|
||||||
def transfer_offsite_backup(job_id):
|
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)
|
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(
|
def dispatch_provisioning_jobs(
|
||||||
model, task, queue, *, lease=REDISPATCH_AFTER, condition=None, **scope
|
model, task, queue, *, lease=REDISPATCH_AFTER, condition=None, **scope
|
||||||
):
|
):
|
||||||
|
|||||||
@@ -11,6 +11,8 @@
|
|||||||
<td>
|
<td>
|
||||||
{% if job.scheduled_for %}
|
{% if job.scheduled_for %}
|
||||||
Scheduled <time datetime="{{ job.scheduled_for|date:"c" }}">{{ job.scheduled_for|date:"j M Y, H:i" }} UTC</time>
|
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 %}
|
{% else %}
|
||||||
Manual
|
Manual
|
||||||
{% endif %}
|
{% endif %}
|
||||||
@@ -39,6 +41,25 @@
|
|||||||
<div>Account ID <code>{{ job.account_id }}</code></div>
|
<div>Account ID <code>{{ job.account_id }}</code></div>
|
||||||
<div>Destination ID <code>{{ transfer.destination }}</code></div>
|
<div>Destination ID <code>{{ transfer.destination }}</code></div>
|
||||||
</details>
|
</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 %}
|
{% elif transfer.problem %}
|
||||||
<div>{{ transfer.problem }}</div>
|
<div>{{ transfer.problem }}</div>
|
||||||
{% if can_retry_offsite and transfer.status == "Failed" %}
|
{% if can_retry_offsite and transfer.status == "Failed" %}
|
||||||
|
|||||||
@@ -22,6 +22,15 @@
|
|||||||
{% if account_backup_allow_mail %}
|
{% if account_backup_allow_mail %}
|
||||||
<label><input type="checkbox" name="include_mail" value="1"> Include mailboxes</label>
|
<label><input type="checkbox" name="include_mail" value="1"> Include mailboxes</label>
|
||||||
{% endif %}
|
{% 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>
|
<button class="button primary" type="submit">Create backup</button>
|
||||||
</form>
|
</form>
|
||||||
{% endif %}
|
{% endif %}
|
||||||
|
|||||||
@@ -7,7 +7,10 @@
|
|||||||
<section class="surface" aria-labelledby="installation-heading">
|
<section class="surface" aria-labelledby="installation-heading">
|
||||||
<header class="section-heading"><h2 id="installation-heading">Installation</h2></header>
|
<header class="section-heading"><h2 id="installation-heading">Installation</h2></header>
|
||||||
<dl class="details">
|
<dl class="details">
|
||||||
<div><dt>Installed version</dt><dd>{{ installed_version }}</dd></div>
|
<div><dt>{% if panel_extension_versions %}Core version{% else %}Installed version{% endif %}</dt><dd>{{ installed_version }}</dd></div>
|
||||||
|
{% for label, version in panel_extension_versions %}
|
||||||
|
<div><dt>{{ label }}</dt><dd>{{ version }}</dd></div>
|
||||||
|
{% endfor %}
|
||||||
{% if request.user.is_superuser %}
|
{% if request.user.is_superuser %}
|
||||||
<div><dt>Release history</dt><dd><a href="{% url 'panel:changelog' %}">Changelog</a></dd></div>
|
<div><dt>Release history</dt><dd><a href="{% url 'panel:changelog' %}">Changelog</a></dd></div>
|
||||||
{% endif %}
|
{% endif %}
|
||||||
|
|||||||
@@ -1,6 +1,9 @@
|
|||||||
import json
|
import json
|
||||||
|
import os
|
||||||
from datetime import timedelta
|
from datetime import timedelta
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
|
from tempfile import TemporaryDirectory
|
||||||
|
from types import SimpleNamespace
|
||||||
from unittest.mock import patch
|
from unittest.mock import patch
|
||||||
from uuid import uuid4
|
from uuid import uuid4
|
||||||
|
|
||||||
@@ -11,19 +14,35 @@ from django.urls import reverse
|
|||||||
from django.utils import timezone
|
from django.utils import timezone
|
||||||
|
|
||||||
from coulobre.account_backup import AccountBackup
|
from coulobre.account_backup import AccountBackup
|
||||||
from coulobre.offsite_backup import OffsiteBackupRequest, destination_labels
|
from coulobre.offsite_backup import (
|
||||||
from coulobre.offsite_node import OffsiteRepositoryError, Repository
|
OffsiteBackupRequest,
|
||||||
|
OffsiteRecoveryRequest,
|
||||||
|
destination_labels,
|
||||||
|
)
|
||||||
|
from coulobre.offsite_node import (
|
||||||
|
OffsiteRepositoryError,
|
||||||
|
Repository,
|
||||||
|
recover_offsite_backup,
|
||||||
|
)
|
||||||
from coulobre.web_node import WebSite
|
from coulobre.web_node import WebSite
|
||||||
|
|
||||||
|
from . import offsite_destinations as catalog
|
||||||
from .account_backups import queue_account_backup, queue_due_account_backups
|
from .account_backups import queue_account_backup, queue_due_account_backups
|
||||||
from .backup_retention import plan_backup_expirations
|
from .backup_retention import plan_backup_expirations
|
||||||
from .models import (
|
from .models import (
|
||||||
AccountBackupExpiration,
|
AccountBackupExpiration,
|
||||||
HostingAccount,
|
HostingAccount,
|
||||||
|
OffsiteBackupRecovery,
|
||||||
OffsiteBackupTransfer,
|
OffsiteBackupTransfer,
|
||||||
)
|
)
|
||||||
from .offsite_backups import MAX_ATTEMPTS, OFFSITE_BACKUP_QUEUE
|
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):
|
class OffsiteRepositoryTests(SimpleTestCase):
|
||||||
@@ -68,6 +87,73 @@ class OffsiteRepositoryTests(SimpleTestCase):
|
|||||||
):
|
):
|
||||||
repository.snapshot(request)
|
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(
|
@override_settings(
|
||||||
LOCAL_ACCOUNT_BACKUPS=True,
|
LOCAL_ACCOUNT_BACKUPS=True,
|
||||||
@@ -119,7 +205,7 @@ class OffsiteBackupWorkflowTests(TestCase):
|
|||||||
**values,
|
**values,
|
||||||
)
|
)
|
||||||
|
|
||||||
def test_only_scheduled_backups_capture_the_configured_destination(self):
|
def test_schedules_capture_the_configured_destination(self):
|
||||||
response = self.client.post(
|
response = self.client.post(
|
||||||
self.schedule,
|
self.schedule,
|
||||||
{
|
{
|
||||||
@@ -160,6 +246,117 @@ class OffsiteBackupWorkflowTests(TestCase):
|
|||||||
"Select a valid choice",
|
"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):
|
def test_only_finished_local_archives_are_dispatched(self):
|
||||||
ready = self.transfer()
|
ready = self.transfer()
|
||||||
self.transfer(self.archive(finished_at=None))
|
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>")
|
||||||
@@ -7,6 +7,7 @@ from unittest.mock import patch
|
|||||||
from django.contrib.auth import get_user_model
|
from django.contrib.auth import get_user_model
|
||||||
from django.contrib.auth.models import Permission
|
from django.contrib.auth.models import Permission
|
||||||
from django.core.management import call_command
|
from django.core.management import call_command
|
||||||
|
from django.template.loader import render_to_string
|
||||||
from django.test import SimpleTestCase, TestCase, override_settings
|
from django.test import SimpleTestCase, TestCase, override_settings
|
||||||
from django.urls import reverse
|
from django.urls import reverse
|
||||||
from django.utils import timezone
|
from django.utils import timezone
|
||||||
@@ -237,6 +238,8 @@ class ServiceHealthPanelTests(TestCase):
|
|||||||
):
|
):
|
||||||
response = self.client.get(url)
|
response = self.client.get(url)
|
||||||
self.assertContains(response, "1.2.3")
|
self.assertContains(response, "1.2.3")
|
||||||
|
self.assertContains(response, "<dt>Installed version</dt>", html=True)
|
||||||
|
self.assertNotContains(response, "<dt>Core version</dt>", html=True)
|
||||||
self.assertContains(response, "Apache License 2.0")
|
self.assertContains(response, "Apache License 2.0")
|
||||||
self.assertContains(response, reverse("panel:service_health"))
|
self.assertContains(response, reverse("panel:service_health"))
|
||||||
features = {
|
features = {
|
||||||
@@ -248,6 +251,25 @@ class ServiceHealthPanelTests(TestCase):
|
|||||||
self.assertNotContains(response, "test-only-bridge-key")
|
self.assertNotContains(response, "test-only-bridge-key")
|
||||||
self.assertNotContains(response, "https://webmail.example.net")
|
self.assertNotContains(response, "https://webmail.example.net")
|
||||||
|
|
||||||
|
def test_installation_labels_core_and_extension_versions_separately(self):
|
||||||
|
self.client.force_login(self.operator)
|
||||||
|
response = self.client.get(reverse("panel:installation"))
|
||||||
|
html = render_to_string(
|
||||||
|
response.template_name,
|
||||||
|
response.context_data
|
||||||
|
| {
|
||||||
|
"installed_version": "1.2.3",
|
||||||
|
"panel_extension_versions": [("Example version", "4.5.6")],
|
||||||
|
},
|
||||||
|
request=response.wsgi_request,
|
||||||
|
)
|
||||||
|
self.assertInHTML(
|
||||||
|
"<div><dt>Core version</dt><dd>1.2.3</dd></div>", html
|
||||||
|
)
|
||||||
|
self.assertInHTML(
|
||||||
|
"<div><dt>Example version</dt><dd>4.5.6</dd></div>", html
|
||||||
|
)
|
||||||
|
|
||||||
@override_settings(
|
@override_settings(
|
||||||
LOCAL_DNS_PUBLISHING=True,
|
LOCAL_DNS_PUBLISHING=True,
|
||||||
HOSTING_NAMESERVERS=(),
|
HOSTING_NAMESERVERS=(),
|
||||||
|
|||||||
@@ -576,6 +576,11 @@ urlpatterns = [
|
|||||||
views.RetryOffsiteBackup.as_view(),
|
views.RetryOffsiteBackup.as_view(),
|
||||||
name="retry_offsite_backup",
|
name="retry_offsite_backup",
|
||||||
),
|
),
|
||||||
|
path(
|
||||||
|
"accounts/<int:pk>/backups/<int:backup_pk>/offsite/recover/",
|
||||||
|
views.RecoverOffsiteBackup.as_view(),
|
||||||
|
name="recover_offsite_backup",
|
||||||
|
),
|
||||||
path(
|
path(
|
||||||
"accounts/<int:pk>/backups/retention/",
|
"accounts/<int:pk>/backups/retention/",
|
||||||
views.EditBackupRetention.as_view(),
|
views.EditBackupRetention.as_view(),
|
||||||
|
|||||||
@@ -126,7 +126,8 @@ from .models import (
|
|||||||
WebsiteDomain,
|
WebsiteDomain,
|
||||||
WebsiteRestoreJob,
|
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 (
|
from .php_settings import (
|
||||||
SitePhpSettingsForm,
|
SitePhpSettingsForm,
|
||||||
last_applied_php_settings,
|
last_applied_php_settings,
|
||||||
@@ -834,6 +835,8 @@ class AccountDetail(TenantScopeMixin, PermissionRequiredMixin, DetailView):
|
|||||||
context["can_retry_offsite"] = panel_feature_allowed(
|
context["can_retry_offsite"] = panel_feature_allowed(
|
||||||
"OFFSITE_BACKUP_DESTINATIONS"
|
"OFFSITE_BACKUP_DESTINATIONS"
|
||||||
) and user.has_perms(RETRY_OFFSITE_BACKUP)
|
) and user.has_perms(RETRY_OFFSITE_BACKUP)
|
||||||
|
if context["can_retry_offsite"]:
|
||||||
|
context["backup_destinations"] = offsite_destinations()
|
||||||
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)
|
||||||
@@ -1422,6 +1425,16 @@ class RequestAccountBackup(OperatorOnlyMixin, PermissionRequiredMixin, View):
|
|||||||
def post(self, request, pk):
|
def post(self, request, pk):
|
||||||
if not panel_feature_allowed("LOCAL_ACCOUNT_BACKUPS"):
|
if not panel_feature_allowed("LOCAL_ACCOUNT_BACKUPS"):
|
||||||
raise Http404
|
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"
|
include_mailboxes = request.POST.get("include_mail") == "1"
|
||||||
if include_mailboxes:
|
if include_mailboxes:
|
||||||
if not mail_backups_enabled():
|
if not mail_backups_enabled():
|
||||||
@@ -1429,7 +1442,11 @@ class RequestAccountBackup(OperatorOnlyMixin, PermissionRequiredMixin, View):
|
|||||||
if not request.user.has_perm(VIEW_MAILBOXES):
|
if not request.user.has_perm(VIEW_MAILBOXES):
|
||||||
return self.handle_no_permission()
|
return self.handle_no_permission()
|
||||||
try:
|
try:
|
||||||
queue_account_backup(pk, include_mailboxes=include_mailboxes)
|
queue_account_backup(
|
||||||
|
pk,
|
||||||
|
include_mailboxes=include_mailboxes,
|
||||||
|
offsite_destination=destination,
|
||||||
|
)
|
||||||
except HostingAccount.DoesNotExist:
|
except HostingAccount.DoesNotExist:
|
||||||
raise Http404 from None
|
raise Http404 from None
|
||||||
except ValidationError as error:
|
except ValidationError as error:
|
||||||
@@ -1439,7 +1456,7 @@ class RequestAccountBackup(OperatorOnlyMixin, PermissionRequiredMixin, View):
|
|||||||
|
|
||||||
def visible_account_backups(account, user):
|
def visible_account_backups(account, user):
|
||||||
backups = account.backup_jobs.select_related(
|
backups = account.backup_jobs.select_related(
|
||||||
"expiration", "offsite_transfer"
|
"expiration", "offsite_transfer__recovery", "offsite_recovery"
|
||||||
).order_by("-requested_at", "-pk")
|
).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")
|
||||||
@@ -1512,6 +1529,27 @@ class RetryOffsiteBackup(OperatorOnlyMixin, PermissionRequiredMixin, View):
|
|||||||
return redirect("panel:account_backup_archives", pk=pk)
|
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(
|
class BackupRetentionView(
|
||||||
OperatorOnlyMixin, PermissionRequiredMixin, FormView
|
OperatorOnlyMixin, PermissionRequiredMixin, FormView
|
||||||
):
|
):
|
||||||
|
|||||||
@@ -80,3 +80,66 @@ class OffsiteBackupRequest:
|
|||||||
@property
|
@property
|
||||||
def archive_name(self):
|
def archive_name(self):
|
||||||
return f"account-{self.account_id}-{self.backup_id}.zip"
|
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,
|
||||||
|
}
|
||||||
@@ -10,7 +10,10 @@ from tempfile import NamedTemporaryFile
|
|||||||
from zipfile import BadZipFile
|
from zipfile import BadZipFile
|
||||||
|
|
||||||
from .account_backup import open_account_bundle, private_path
|
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 (
|
from .node_files import (
|
||||||
check_root_file,
|
check_root_file,
|
||||||
locked_root_directory,
|
locked_root_directory,
|
||||||
@@ -22,6 +25,7 @@ from .offsite_backup import (
|
|||||||
HEX_DIGEST,
|
HEX_DIGEST,
|
||||||
TRANSFER_TIMEOUT_SECONDS,
|
TRANSFER_TIMEOUT_SECONDS,
|
||||||
OffsiteBackupRequest,
|
OffsiteBackupRequest,
|
||||||
|
OffsiteRecoveryRequest,
|
||||||
validate_destination,
|
validate_destination,
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -230,16 +234,22 @@ def verify_destination(destination):
|
|||||||
Repository.for_destination(destination).run("cat", "config")
|
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)
|
repository = Repository.for_destination(request.destination)
|
||||||
snapshot = repository.snapshot(request)
|
snapshot = repository.snapshot(request)
|
||||||
if snapshot is None:
|
if snapshot is None:
|
||||||
raise ValueError("No off-site snapshot matches this backup ID.")
|
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)
|
output = private_path(output, new=True)
|
||||||
snapshot_id, digest = snapshot
|
snapshot_id, digest = snapshot
|
||||||
with NamedTemporaryFile(dir=output.parent) as staged:
|
with NamedTemporaryFile(dir=output.parent) as staged:
|
||||||
recovered = repository.read_archive(
|
recovered = repository.read_archive(
|
||||||
request, snapshot_id, target=staged
|
request, snapshot_id, target=staged, expected_size=expected_size
|
||||||
)
|
)
|
||||||
if recovered != digest:
|
if recovered != digest:
|
||||||
raise ValueError(
|
raise ValueError(
|
||||||
@@ -254,15 +264,46 @@ def recover_offsite_backup(request, output):
|
|||||||
return snapshot_id
|
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 serve_offsite_request():
|
||||||
def apply(request):
|
def apply(request):
|
||||||
try:
|
try:
|
||||||
|
if isinstance(request, OffsiteRecoveryRequest):
|
||||||
|
return recover_for_panel(request)
|
||||||
return transfer_offsite_backup(request)
|
return transfer_offsite_backup(request)
|
||||||
except OSError:
|
except (BadZipFile, OSError):
|
||||||
raise ValueError(
|
raise ValueError(
|
||||||
"The backup node could not access the archive or destination."
|
"The backup node could not access the archive or destination."
|
||||||
) from None
|
) from None
|
||||||
|
|
||||||
return serve_apply_request(
|
return serve_apply_request(
|
||||||
1, OffsiteBackupRequest.from_manifest, apply, include_result=True
|
1, parse_offsite_request, apply, include_result=True
|
||||||
)
|
)
|
||||||
@@ -519,7 +519,7 @@ if LOCAL_BACKUP_RETENTION:
|
|||||||
"schedule": 300.0,
|
"schedule": 300.0,
|
||||||
"options": {"expires": 295.0},
|
"options": {"expires": 295.0},
|
||||||
}
|
}
|
||||||
if LOCAL_ACCOUNT_BACKUPS and OFFSITE_BACKUP_DESTINATIONS:
|
if LOCAL_ACCOUNT_BACKUPS:
|
||||||
CELERY_BEAT_SCHEDULE["dispatch-offsite-backups"] = {
|
CELERY_BEAT_SCHEDULE["dispatch-offsite-backups"] = {
|
||||||
"task": "coulobre.hosting.tasks.dispatch_offsite_backups",
|
"task": "coulobre.hosting.tasks.dispatch_offsite_backups",
|
||||||
"schedule": 15.0,
|
"schedule": 15.0,
|
||||||
|
|||||||
Reference in new issue
Block a user