Apply selected WordPress updates with a recovery backup #239

Merged
parkel merged 3 commits from feature/wordpress-updates into main 2026-12-02 01:29:37 +01:00
16 changed files with 874 additions and 43 deletions

No files matched your search

+25 -1
View File
@@ -1390,7 +1390,7 @@ an archive containing several sites. The archive identifies each website
by domain and site ID. Upgrade the panel and its web and backup workers
together before enabling additional sites.
## Enable WordPress installation and administrator setup
## Enable WordPress management
Install the verified [WP-CLI Phar](https://make.wordpress.org/cli/handbook/guides/installing/#verifying-the-download-optional-but-recommended)
as a root-owned regular file at `/usr/local/bin/wp` on the web node.
@@ -1417,6 +1417,30 @@ configuration. If the panel reports an email failure, correct the
site's outbound mail and use the WordPress password reset page. The
setup workflow keeps passwords out of panel jobs, logs and email.
### Update WordPress, plugins and themes
Use WP-CLI 2.10 or later for fresh core update checks. Open the site's
**WordPress** page, select **Check for updates**, and review the installed
and available versions. Select **Back up and update** for one component
at a time. The panel offers stable releases from WordPress.org. Use
WordPress to manage extensions from other sources.
Updates require HTTPS, a single-site installation with its configuration
in the site's document root, and a local MariaDB database managed by
the hosting account. Enable local account backups and the website and
database restore services. Coulobre creates a recovery archive with the
selected document root and the entire database before applying the
update, and checks that the advertised version is still available.
Use a dedicated database for each WordPress site so that restoring its
database does not replace tables for another application.
If an update fails after it starts, use the matching archive in
**Backup & Restore** to recover the document root and database as needed.
Customers can restore their own update backups. Update backups do not
replace the customer's latest SFTP export. Managers can ask the server
operator to restore a backup they requested. Schedule updates during a
quiet period because WordPress may briefly display a maintenance page.
## Enable the website file manager
The installer enables the file manager, scheduled website jobs and local
+23 -7
View File
@@ -21,6 +21,7 @@ BASE_MANIFEST_VERSION = 1
MAIL_MANIFEST_VERSION = 2
MULTI_SITE_MANIFEST_VERSION = 3
SELECTIVE_MANIFEST_VERSION = 4
INDEPENDENT_ONLY_MANIFEST_VERSION = 5
MANIFEST_KIND = "coulobre_account_backup"
MANIFEST_NAME = "manifest.json"
MAX_MANIFEST_BYTES = 1024 * 1024
@@ -36,9 +37,7 @@ class AccountBackup:
include_website: bool = True
def __post_init__(self):
if type(self.include_website) is not bool or (
not self.include_website and self.additional_websites
):
if type(self.include_website) is not bool:
raise ValueError("Choose whether to include the account websites.")
if self.website.site_id is not None:
raise ValueError(
@@ -90,7 +89,11 @@ class AccountBackup:
site.manifest() for site in self.additional_websites
]
if not self.include_website:
manifest["version"] = SELECTIVE_MANIFEST_VERSION
manifest["version"] = (
INDEPENDENT_ONLY_MANIFEST_VERSION
if self.additional_websites
else SELECTIVE_MANIFEST_VERSION
)
manifest["include_website"] = False
return manifest
@@ -104,18 +107,29 @@ class AccountBackup:
MAIL_MANIFEST_VERSION,
MULTI_SITE_MANIFEST_VERSION,
SELECTIVE_MANIFEST_VERSION,
INDEPENDENT_ONLY_MANIFEST_VERSION,
):
raise ValueError("Unsupported account backup manifest version.")
fields = {"version", "kind", "website", "databases"}
if version == MULTI_SITE_MANIFEST_VERSION:
if version in (
MULTI_SITE_MANIFEST_VERSION,
INDEPENDENT_ONLY_MANIFEST_VERSION,
):
fields.add("additional_websites")
if version == SELECTIVE_MANIFEST_VERSION:
if version in (
SELECTIVE_MANIFEST_VERSION,
INDEPENDENT_ONLY_MANIFEST_VERSION,
):
fields.add("include_website")
if data.get("include_website") is not False:
raise ValueError("Expected a selective account backup.")
if version == MAIL_MANIFEST_VERSION or (
version
in (MULTI_SITE_MANIFEST_VERSION, SELECTIVE_MANIFEST_VERSION)
in (
MULTI_SITE_MANIFEST_VERSION,
SELECTIVE_MANIFEST_VERSION,
INDEPENDENT_ONLY_MANIFEST_VERSION,
)
and "mailboxes" in data
):
fields.add("mailboxes")
@@ -133,6 +147,8 @@ class AccountBackup:
raise ValueError(
"Expected a list of additional website manifests."
)
if version == INDEPENDENT_ONLY_MANIFEST_VERSION and not sites:
raise ValueError("Expected at least one independent website.")
return cls(
WebSite.from_manifest(data["website"]),
tuple(
+12
View File
@@ -80,6 +80,15 @@ def available_website_restore_targets(backup, current=None):
}
def require_no_wordpress_update(account):
if account.wordpress_jobs.filter(
action="update", finished_at__isnull=True
).exists():
raise ValidationError(
"Wait for the current WordPress update to finish."
)
@transaction.atomic
def queue_website_restore(
backup,
@@ -93,6 +102,7 @@ def queue_website_restore(
):
account = lock_hosting_account(backup.account_id, customer_id=customer_id)
require_active_services(account)
require_no_wordpress_update(account)
backup.refresh_from_db()
if customer_id is not None and backup.export_customer_id != customer_id:
raise ValidationError("This backup is no longer available.")
@@ -130,6 +140,8 @@ def queue_component_restore(
):
account = lock_hosting_account(backup.account_id, customer_id=customer_id)
require_active_services(account)
if kind == RestoreKind.DATABASE:
require_no_wordpress_update(account)
backup.refresh_from_db()
if customer_id is not None and backup.export_customer_id != customer_id:
raise ValidationError("This backup is no longer available.")
@@ -70,7 +70,7 @@ class CustomerBackupView(UserPassesTestMixin, FormView):
export_customer_id=self.account.customer_id,
export_database_suffix="",
)
.select_related("expiration")
.select_related("expiration", "wordpress_update")
.order_by("-requested_at")[:30]
)
kinds = enabled_component_restores()
@@ -0,0 +1,23 @@
# Generated by Django 5.2.19 on 2026-12-02 00:18
import django.db.models.deletion
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("hosting", "0088_wordpress_operation"),
]
operations = [
migrations.AddField(
model_name="wordpressjob",
name="backup",
field=models.OneToOneField(
null=True,
on_delete=django.db.models.deletion.SET_NULL,
related_name="wordpress_update",
to="hosting.accountbackupjob",
),
),
]
+10 -1
View File
@@ -1385,6 +1385,12 @@ class WordPressJob(ProvisioningJob):
database = models.ForeignKey(
HostingDatabase, on_delete=models.SET_NULL, null=True
)
backup = models.OneToOneField(
"AccountBackupJob",
on_delete=models.SET_NULL,
null=True,
related_name="wordpress_update",
)
details = models.JSONField(default=dict)
report = models.JSONField(default=dict)
@@ -1427,7 +1433,10 @@ class AccountBackupJob(ProvisioningJob):
def can_restore_website(self, site):
return self.archive_is_restorable and (
self.manifest.get("website") == site.manifest()
(
self.manifest.get("include_website", True)
and self.manifest.get("website") == site.manifest()
)
or site.manifest() in self.manifest.get("additional_websites", [])
)
+13 -4
View File
@@ -192,8 +192,14 @@ def dispatch_web_activations():
WordPressJob,
run_wordpress_job,
WEB_ACTIVATION_QUEUE,
condition=Q(database__isnull=True)
| Q(database__provisioning__finished_at__isnull=False),
condition=(
Q(database__isnull=True)
| Q(database__provisioning__finished_at__isnull=False)
)
& (
Q(backup__isnull=True)
| Q(backup__finished_at__isnull=False)
),
)
dispatch_provisioning_jobs(
WebsiteRedirectPolicy,
@@ -956,7 +962,10 @@ def create_backup_job_archive(job):
job.backup_id,
backup,
remote_mail=job.remote_mail,
publish_to_customer=job.export_customer_id is not None,
publish_to_customer=(
job.export_customer_id is not None
and not hasattr(job, "wordpress_update")
),
database_suffix=job.export_database_suffix,
)
)
@@ -1155,7 +1164,7 @@ def run_wordpress_job(job_id):
if settings.WORDPRESS_MANAGEMENT and settings.LOCAL_WEB_ACTIVATION:
run_provisioning_job(
WordPressJob.objects.select_related(
"account", "actor", "database"
"account", "actor", "database", "backup", "backup__expiration"
),
job_id,
run_wordpress_operation,
@@ -41,18 +41,69 @@
<input type="hidden" name="site" value="{{ site.domain }}">
<button class="button secondary" name="action" value="inspect" type="submit">Detect WordPress</button>
</form>
{% if version %}
<header class="section-heading">
<div>
<h2>WordPress.org updates</h2>
<p class="heading-meta">Coulobre backs up this website and its database before applying each update.</p>
</div>
<form method="post">
{% csrf_token %}
<input type="hidden" name="site" value="{{ site.domain }}">
<button class="button secondary" name="action" value="check-updates" type="submit"{% if jobs and not jobs.0.finished_at %} disabled{% endif %}>Check for updates</button>
</form>
</header>
{% if inventory.updates %}
{% if not updates_can_recover %}
<p class="section-text">Ask your server operator to enable website and database recovery before updating.</p>
{% elif not updates_has_database %}
<p class="section-text">Panel updates require a local database managed by this hosting account.</p>
{% endif %}
<div class="table-scroll">
<table>
<thead><tr><th scope="col">Component</th><th scope="col">Installed</th><th scope="col">Available</th><th scope="col">Actions</th></tr></thead>
<tbody>
{% for update in inventory.updates %}
<tr>
<th scope="row">{% if update.kind == "core" %}WordPress core{% else %}{{ update.slug }} · {{ update.kind }}{% endif %}</th>
<td>{{ update.installed }}</td>
<td>{{ update.version }}</td>
<td>
{% if updates_can_recover and updates_has_database %}
<form method="post">
{% csrf_token %}
<input type="hidden" name="site" value="{{ site.domain }}">
<input type="hidden" name="selection" value="{{ update.kind }}:{{ update.slug }}:{{ update.installed }}:{{ update.version }}">
<button class="button secondary" name="action" value="update" type="submit"{% if jobs and not jobs.0.finished_at %} disabled{% endif %}>Back up and update</button>
</form>
{% else %}—{% endif %}
</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
{% elif inventory %}
<p class="section-text">No available WordPress.org updates were reported.</p>
{% endif %}
{% endif %}
{% if jobs %}
<header class="section-heading"><h2>Operation history</h2></header>
<div class="table-scroll">
<table>
<thead><tr><th scope="col">Operation</th><th scope="col">Requested</th><th scope="col">Result</th></tr></thead>
<tbody>
{% for job in jobs %}
<tr>
<th scope="row">{% if job.action == "add-admin" %}Add administrator{% elif job.action == "install" %}Install{% else %}Detect{% endif %}</th>
<th scope="row">{% if job.action == "add-admin" %}Add administrator{% elif job.action == "install" %}Install{% elif job.action == "check-updates" %}Check for updates{% elif job.action == "update" %}Update {{ job.details.update.slug }} to {{ job.details.update.version }}{% else %}Detect{% endif %}</th>
<td>{{ job.requested_at }}</td>
<td>
{% if job.problem %}{{ job.problem }}
{% else %}{{ job.state|capfirst }}{% endif %}
{% if job.backup %}
<br>Recovery backup requested {{ job.backup.requested_at }} · {{ job.backup.state|capfirst }}.
{% if recovery_route %}<a href="{% url recovery_route account.pk %}">Backup &amp; Restore</a>{% else %}Contact your server operator to restore it.{% endif %}
{% endif %}
{% if job.report.password_email == "accepted" %}<br>WordPress accepted the password setup email.
{% elif job.report.password_email == "failed" %}<br>WordPress could not send the setup email. Check the website's mail settings and <a href="https://{{ site.domain }}/wp-login.php?action=lostpassword">request a password reset</a>.
{% endif %}
@@ -12,7 +12,7 @@
<section class="surface" aria-labelledby="backup-history" data-live-status="customer-backups">
<header class="section-heading"><h2 id="backup-history">Recent backups</h2></header>
<ul class="workspace-list">
{% for backup, kinds in backups %}<li>{{ backup.requested_at|date:"j M Y H:i" }} · {{ backup.state|capfirst }}
{% for backup, kinds in backups %}<li>{{ backup.requested_at|date:"j M Y H:i" }} · {{ backup.state|capfirst }}{% if backup.wordpress_update %} · WordPress recovery backup{% endif %}
{% for kind in kinds %}<a class="button secondary" href="{% url 'panel:customer_restore' account.pk backup.pk kind %}">Restore {{ kind }}</a>{% endfor %}
</li>
{% empty %}<li>No backups yet.</li>{% endfor %}
+218 -1
View File
@@ -1,17 +1,26 @@
from pathlib import Path
from subprocess import CompletedProcess
from tempfile import TemporaryDirectory
from unittest.mock import patch
from unittest.mock import Mock, call, patch
from uuid import uuid4
from zipfile import ZipFile
from django.contrib.auth import get_user_model
from django.test import SimpleTestCase, TestCase, override_settings
from django.urls import reverse
from django.utils import timezone
from coulobre.account_backup import MANIFEST_NAME, AccountBackup, manifest_text
from coulobre.database_node import DatabaseSpec
from coulobre.web_node import WebSite, parse_web_request
from coulobre.web_node_apply import STARTER_PAGE
from coulobre.wordpress import WordPressRequest
from coulobre.wordpress_node import check_install_target, publish_wordpress
from coulobre.wordpress_node_updates import (
apply_update,
verify_recovery_archive,
)
from coulobre.wordpress_updates import WordPressUpdate
from .models import (
Customer,
@@ -54,6 +63,66 @@ class InstallRequestTests(SimpleTestCase):
email="owner@example.test",
)
def test_independent_update_archive_cannot_restore_the_primary_site(self):
primary = WebSite(7, "primary.test")
site = WebSite(7, "wordpress.test", 9)
database = DatabaseSpec(site.account_id, "wp")
request = WordPressRequest(
site,
"update",
database,
update={
"kind": "core",
"slug": "wordpress",
"installed": "7.0",
"version": "7.1",
},
backup_id=str(uuid4()),
)
self.assertEqual(parse_web_request(request.manifest()), request)
with self.assertRaisesRegex(ValueError, "Invalid WordPress update"):
parse_web_request(
request.manifest()
| {
"update": request.update | {"slug": "--force"},
}
)
backup = AccountBackup(
primary,
(database,),
additional_websites=(site,),
include_website=False,
)
self.assertEqual(
AccountBackup.from_manifest(backup.manifest()), backup
)
self.assertEqual(
[resource for resource, _, _ in backup.components()],
[site, database],
)
with TemporaryDirectory() as work:
archive = Path(work) / "backup.zip"
with (
patch(
"coulobre.wordpress_node_updates.backup_archive",
return_value=archive,
),
patch(
"coulobre.account_backup.private_path",
side_effect=lambda path: path,
),
patch("coulobre.account_backup.check_root_file"),
):
with self.assertRaisesRegex(
ValueError, "archive is unavailable"
):
verify_recovery_archive(request)
with ZipFile(archive, "w") as bundle:
bundle.writestr(MANIFEST_NAME, manifest_text(backup))
for _, _, component in backup.components():
bundle.writestr(component, b"example content")
verify_recovery_archive(request)
def test_install_replaces_only_the_unmodified_starter_page(self):
with TemporaryDirectory() as work:
root = Path(work)
@@ -191,3 +260,151 @@ class WordPressWorkflowTests(TestCase):
enqueue.assert_called_once_with(
args=[job.pk], queue="coulobre-web-activation", retry=False
)
@override_settings(
LOCAL_ACCOUNT_BACKUPS=True,
LOCAL_WEBSITE_RESTORE=True,
LOCAL_DATABASE_RESTORE=True,
)
@patch("coulobre.hosting.node_client.apply_on_local_node")
@patch.object(run_wordpress_job, "apply_async")
def test_update_waits_for_a_recovery_backup_of_the_selected_site_and_db(
self, enqueue, apply
):
self.client.post(self.url, self.data)
install = self.account.wordpress_jobs.get()
provisioning = install.database.provisioning
provisioning.finished_at = timezone.now()
provisioning.save(update_fields=["finished_at"])
apply.return_value = {"wp_version": "7.0"}
run_wordpress_job.run(install.pk)
self.client.post(self.url, self.data | {"action": "check-updates"})
check = self.account.wordpress_jobs.latest("pk")
selection = {
"kind": "plugin",
"slug": "akismet",
"installed": "5.0",
"version": "5.1",
}
apply.return_value = {
"wp_version": "7.0",
"database_name": install.database.spec.name,
"updates": [selection],
}
run_wordpress_job.run(check.pk)
self.assertContains(self.client.get(self.url), "Back up and update")
request = self.data | {"action": "update"}
response = self.client.post(
self.url, request | {"selection": "plugin:akismet:5.0:5.2"}
)
self.assertContains(response, "select an available version again")
self.assertFalse(self.account.backup_jobs.exists())
request["selection"] = "plugin:akismet:5.0:5.1"
self.assertEqual(self.client.post(self.url, request).status_code, 302)
update = self.account.wordpress_jobs.latest("pk")
backup = update.backup
self.assertEqual(update.database_id, install.database_id)
self.assertEqual(backup.export_customer_id, self.customer.pk)
self.assertEqual(backup.manifest["website"], update.site)
self.assertEqual(
backup.manifest["databases"], [install.database.spec.manifest()]
)
dispatch_web_activations.run()
enqueue.assert_not_called()
backup.finished_at = timezone.now()
backup.problem = "Backup worker could not archive the files."
backup.save(update_fields=["finished_at", "problem"])
dispatch_web_activations.run()
enqueue.assert_called_once_with(
args=[update.pk], queue="coulobre-web-activation", retry=False
)
apply.reset_mock()
run_wordpress_job.run(update.pk)
apply.assert_not_called()
update.refresh_from_db()
self.assertEqual(update.state, "failed")
self.assertIn("recovery backup is unavailable", update.problem)
self.client.post(self.url, self.data | {"action": "check-updates"})
run_wordpress_job.run(self.account.wordpress_jobs.latest("pk").pk)
self.assertEqual(self.client.post(self.url, request).status_code, 302)
second = self.account.wordpress_jobs.latest("pk")
second.backup.finished_at = timezone.now()
second.backup.save(update_fields=["finished_at"])
apply.return_value = {"wp_version": "7.0"}
run_wordpress_job.run(second.pk)
second.refresh_from_db()
self.assertEqual(second.state, "configured")
self.assertEqual(apply.call_args.args[0].update, selection)
self.assertEqual(
apply.call_args.args[0].backup_id, str(second.backup.backup_id)
)
response = self.client.get(
reverse("panel:customer_backups", args=[self.account.pk])
)
self.assertContains(response, "WordPress recovery backup")
self.assertContains(response, "Restore database")
class UpdateCommandTests(SimpleTestCase):
@patch("coulobre.wordpress_node_updates.verify_recovery_archive")
@patch("coulobre.wordpress_node_updates.database_name")
@patch("coulobre.wordpress_node_updates.update_inventory")
def test_selected_core_and_theme_commands_use_the_exact_version(
self, inventory, database_name, verify_archive
):
site = WebSite(7, "wordpress.test")
database = DatabaseSpec(site.account_id, "wp")
database_name.return_value = database.name
root = Path("/website")
for kind, slug, commands in (
(
"core",
"wordpress",
[("core", "update", "--version=3.1"), ("core", "update-db")],
),
(
"theme",
"example",
[
("theme", "update", "example", "--version=3.1"),
("theme", "get", "example", "--field=version"),
],
),
):
with self.subTest(kind=kind):
update = WordPressUpdate(kind, slug, "3.0", "3.1")
request = WordPressRequest(
site,
"update",
database,
update=update.manifest(),
backup_id=str(uuid4()),
)
inventory.return_value = [update]
cli = Mock()
cli.require.return_value = CompletedProcess(
args=(), returncode=0, stdout=b"3.1\n"
)
apply_update(request, cli, root, "3.0")
self.assertEqual(verify_archive.call_args, call(request))
self.assertEqual(
inventory.call_args, call(cli, root, "3.0", kind)
)
self.assertEqual(
[
invocation.args[2:]
for invocation in cli.require.call_args_list
],
commands,
)
inventory.return_value = []
cli.reset_mock()
with self.assertRaisesRegex(
ValueError, "selected update changed"
):
apply_update(request, cli, root, "3.0")
cli.require.assert_not_called()
+134 -12
View File
@@ -1,3 +1,4 @@
from datetime import timedelta
from secrets import token_hex
from django.conf import settings
@@ -5,12 +6,15 @@ from django.core.exceptions import PermissionDenied, ValidationError
from django.db import transaction
from django.utils import timezone
from coulobre.account_backup import AccountBackup
from coulobre.web_node import WebSite
from coulobre.wordpress import VERSION, WordPressRequest
from coulobre.wordpress_updates import validate_update_inventory
from .access import customer_for_user, manages_account, reseller_for_user
from .backup_restores import RestoreKind, require_no_wordpress_update
from .installation_features import panel_feature_allowed
from .models import WordPressJob
from .models import ComponentRestoreJob, WebsiteRestoreJob, WordPressJob
from .panel_roles import assigned_roles, scoped_user
from .resource_requests import (
create_database_request,
@@ -18,6 +22,8 @@ from .resource_requests import (
require_active_services,
)
UPDATE_INVENTORY_AGE = timedelta(minutes=30)
PERMISSIONS = (
"hosting.view_hostingaccount",
"hosting.change_hostingaccount",
@@ -55,6 +61,96 @@ def active_sites(account):
return account_certificate_sites(account)
def can_recover_updates():
return (
panel_feature_allowed("LOCAL_ACCOUNT_BACKUPS")
and settings.LOCAL_WEBSITE_RESTORE
and settings.LOCAL_DATABASE_RESTORE
)
def current_update_inventory(jobs):
recent = (
jobs.filter(action__in=("check-updates", "update"))
.order_by("-pk")
.first()
)
if (
recent
and recent.action == "check-updates"
and recent.state == "configured"
and recent.finished_at >= timezone.now() - UPDATE_INVENTORY_AGE
):
return recent.report
return {}
def update_database(account, name):
return (
next(
(
database
for database in account.databases.filter(
provisioning__finished_at__isnull=False,
provisioning__problem="",
)
if database.spec.name == name
),
None,
)
if name
else None
)
def prepare_update_recovery(account, site, actor, jobs, selection):
if not can_recover_updates():
raise ValidationError(
"Enable local website and database recovery first."
)
require_no_wordpress_update(account)
if (
WebsiteRestoreJob.objects.filter(
backup__account=account, finished_at__isnull=True
).exists()
or ComponentRestoreJob.objects.filter(
backup__account=account,
kind=RestoreKind.DATABASE,
finished_at__isnull=True,
).exists()
):
raise ValidationError(
"Wait for the current restore before updating WordPress."
)
inventory = current_update_inventory(jobs)
if selection not in inventory.get("updates", ()):
raise ValidationError(
"Check for updates and select an available version again."
)
database = update_database(account, inventory.get("database_name"))
if database is None:
raise ValidationError(
"Updates require a local database managed by this account."
)
if account.backup_jobs.filter(finished_at__isnull=True).exists():
raise ValidationError(
"Wait for the current backup before updating WordPress."
)
primary = WebSite(account.pk, account.primary_domain)
manifest = AccountBackup(
primary,
(database.spec,),
additional_websites=(site,) if site.site_id else (),
include_website=site.site_id is None,
).manifest()
customer = customer_for_user(actor)
backup = account.backup_jobs.create(
manifest=manifest,
export_customer_id=customer.pk if customer is not None else None,
)
return database, backup
@transaction.atomic
def queue_wordpress_job(account, site, actor, action, details):
account = lock_hosting_account(account.pk, customer_id=None)
@@ -67,7 +163,7 @@ def queue_wordpress_job(account, site, actor, action, details):
jobs = account.wordpress_jobs.filter(site=site.manifest())
if jobs.filter(finished_at__isnull=True).exists():
raise ValidationError("Wait for the current WordPress operation.")
database = None
database = backup = None
if action == "install":
if not panel_feature_allowed("LOCAL_DATABASE_PROVISIONING"):
raise ValidationError(
@@ -93,9 +189,19 @@ def queue_wordpress_job(account, site, actor, action, details):
database = create_database_request(
account.pk, "wp_" + token_hex(4), auto_provision=True
)
elif action == "update":
database, backup = prepare_update_recovery(
account, site, actor, jobs, details.get("update")
)
request_details = details.copy()
if backup is not None:
request_details["backup_id"] = str(backup.backup_id)
try:
WordPressRequest(
site, action, database.spec if database else None, **details
site,
action,
database.spec if database else None,
**request_details,
)
except ValueError as error:
raise ValidationError(str(error)) from error
@@ -107,6 +213,7 @@ def queue_wordpress_job(account, site, actor, action, details):
action=action,
details=details,
database=database,
backup=backup,
)
@@ -127,14 +234,28 @@ def run_wordpress_operation(job):
if active_sites(account).get(site.domain) != site:
raise ValueError("This website is no longer active.")
database = job.database
if job.action == "install" and (
if job.action in ("install", "update") and (
database is None
or database.account_id != account.pk
or database.provisioning.state != "configured"
):
raise ValueError("The WordPress database is not ready.")
details = job.details.copy()
if job.action == "update":
backup = job.backup
if (
not can_recover_updates()
or backup is None
or backup.account_id != account.pk
or not backup.archive_is_restorable
):
raise ValueError(
"The recovery backup is unavailable. "
"Try checking for updates again."
)
details["backup_id"] = str(backup.backup_id)
spec = WordPressRequest(
site, job.action, database.spec if database else None, **job.details
site, job.action, database.spec if database else None, **details
)
reply = apply_on_local_node(
spec,
@@ -148,14 +269,15 @@ def run_wordpress_operation(job):
if (
not isinstance(version, str)
or (version and not VERSION.fullmatch(version))
or (job.action != "inspect" and not version)
or (job.action not in ("inspect", "check-updates") and not version)
or email not in ("", "accepted", "failed")
):
raise ValueError("The web node returned an invalid WordPress report.")
return {
"report": {
"version": version,
"password_email": email,
"checked_at": timezone.now().isoformat(),
}
report = {
"version": version,
"password_email": email,
"checked_at": timezone.now().isoformat(),
}
if job.action == "check-updates":
report.update(validate_update_inventory(reply))
return {"report": report}
+47 -4
View File
@@ -10,15 +10,19 @@ from django.views.decorators.cache import never_cache
from django.views.generic.detail import SingleObjectMixin
from coulobre.wordpress import LOGIN
from coulobre.wordpress_updates import WordPressUpdate
from .access import TenantScopeMixin
from .access import TenantScopeMixin, customer_for_user, is_tenant
from .installation_features import panel_feature_allowed
from .models import HostingAccount
from .wordpress_management import (
PERMISSIONS,
active_sites,
can_manage_wordpress,
can_recover_updates,
current_update_inventory,
queue_wordpress_job,
update_database,
wordpress_available,
)
@@ -36,6 +40,20 @@ class WordPressInstallForm(AdministratorForm):
field_order = ("title", "username", "email", "confirmed")
class WordPressUpdateForm(forms.Form):
selection = forms.CharField(max_length=140)
def clean_selection(self):
try:
return WordPressUpdate(
*self.cleaned_data["selection"].split(":")
).manifest()
except (TypeError, ValueError):
raise ValidationError(
"Choose an available WordPress update."
) from None
@method_decorator(never_cache, name="dispatch")
class AccountWordPressView(
TenantScopeMixin, PermissionRequiredMixin, SingleObjectMixin, View
@@ -76,6 +94,8 @@ class AccountWordPressView(
action = request.POST.get("action")
forms_for_action = {
"inspect": forms.Form,
"check-updates": forms.Form,
"update": WordPressUpdateForm,
"install": WordPressInstallForm,
"add-admin": AdministratorForm,
}
@@ -88,6 +108,8 @@ class AccountWordPressView(
for name, value in form.cleaned_data.items()
if name != "confirmed"
}
if action == "update":
details = {"update": details["selection"]}
try:
queue_wordpress_job(
self.account, self.site, request.user, action, details
@@ -104,16 +126,30 @@ class AccountWordPressView(
def page(self, *, action=None, form=None):
jobs = ()
known_version = ""
inventory = {}
if self.site:
history = self.account.wordpress_jobs.filter(
site=self.site.manifest()
).order_by("-pk")
jobs = list(history[:10])
jobs = list(history.select_related("backup")[:10])
inventory = current_update_inventory(history)
last = history.filter(
finished_at__isnull=False, problem=""
).first()
if last:
known_version = last.report.get("version", "")
user = self.request.user
recovery_route = ""
if customer_for_user(user) is not None:
recovery_route = "panel:customer_backups"
elif not is_tenant(user) and user.has_perms(
(
"hosting.view_webprovisioningplan",
"hosting.view_hostingdatabase",
"hosting.add_accountbackupjob",
)
):
recovery_route = "panel:account_backup_archives"
return render(
self.request,
"hosting/account_wordpress.html",
@@ -123,9 +159,16 @@ class AccountWordPressView(
"site": self.site,
"version": known_version,
"jobs": jobs,
"operation_errors": form.non_field_errors()
if action == "inspect"
"operation_errors": form.errors
if action in ("inspect", "check-updates", "update")
else (),
"inventory": inventory,
"updates_can_recover": can_recover_updates(),
"updates_has_database": update_database(
self.account, inventory.get("database_name")
)
is not None,
"recovery_route": recovery_route,
"install_form": form
if action == "install"
else WordPressInstallForm(
+37 -5
View File
@@ -1,5 +1,6 @@
import re
from dataclasses import dataclass
from uuid import UUID
from django.core.exceptions import ValidationError
from django.core.validators import validate_email
@@ -8,7 +9,7 @@ from .database_node import DatabaseSpec
from .web_node import WebSite
OPERATION = "manage_wordpress"
ACTIONS = ("inspect", "install", "add-admin")
ACTIONS = ("inspect", "install", "add-admin", "check-updates", "update")
LOGIN = re.compile(r"[A-Za-z0-9][A-Za-z0-9._-]{0,59}", re.ASCII)
VERSION = re.compile(r"[0-9][A-Za-z0-9.-]{0,29}", re.ASCII)
@@ -21,15 +22,36 @@ class WordPressRequest:
title: str = ""
username: str = ""
email: str = ""
update: dict | None = None
backup_id: str = ""
def __post_init__(self):
if self.action not in ACTIONS:
raise ValueError("Choose a WordPress action.")
if self.action == "inspect":
if self.action == "update":
from .wordpress_updates import WordPressUpdate
WordPressUpdate.from_manifest(self.update)
if (
self.database is None
or self.database.account_id != self.site.account_id
or any((self.title, self.username, self.email))
):
raise ValueError("Choose a managed database for this website.")
try:
valid_id = str(UUID(self.backup_id)) == self.backup_id
except (TypeError, AttributeError, ValueError):
valid_id = False
if not valid_id:
raise ValueError("Choose a WordPress recovery archive.")
return
if self.update is not None or self.backup_id:
raise ValueError("Unexpected WordPress update details.")
if self.action in ("inspect", "check-updates"):
if self.database is not None or any(
(self.title, self.username, self.email)
):
raise ValueError("Inspect only accepts a website.")
raise ValueError("This operation only accepts a website.")
return
if not isinstance(self.username, str) or not LOGIN.fullmatch(
self.username
@@ -70,12 +92,18 @@ class WordPressRequest:
"site": self.site.manifest(),
"action": self.action,
}
if self.action != "inspect":
if self.action in ("install", "add-admin"):
manifest.update(username=self.username, email=self.email)
if self.action == "install":
manifest.update(
database=self.database.manifest(), title=self.title
)
if self.action == "update":
manifest.update(
database=self.database.manifest(),
update=self.update,
backup_id=self.backup_id,
)
return manifest
@classmethod
@@ -88,15 +116,19 @@ class WordPressRequest:
fields.update(("username", "email"))
if action == "install":
fields.update(("database", "title"))
if action == "update":
fields.update(("database", "update", "backup_id"))
if data.keys() != fields:
raise ValueError("Expected a WordPress request.")
return cls(
WebSite.from_manifest(data["site"]),
action,
DatabaseSpec.from_manifest(data["database"])
if action == "install"
if action in ("install", "update")
else None,
data.get("title", ""),
data.get("username", ""),
data.get("email", ""),
data.get("update"),
data.get("backup_id", ""),
)
+39 -5
View File
@@ -6,6 +6,7 @@ import subprocess
from dataclasses import dataclass
from pathlib import Path
from tempfile import TemporaryDirectory, TemporaryFile
from time import monotonic
from uuid import uuid4
from . import web_node_apply as web
@@ -16,6 +17,12 @@ from .web_node_files import rename_entry
from .web_node_restore import publish_empty_webroot
from .web_node_tls import https_status
from .wordpress import VERSION
from .wordpress_node_updates import (
apply_update,
database_name,
update_inventory,
)
from .wordpress_updates import validate_update_inventory
WP_CLI = Path("/usr/local/bin/wp")
COMMAND_TIMEOUT = 35
@@ -32,6 +39,7 @@ class WordPressCLI:
home: Path
uid: int
gid: int
deadline: float | None = None
def run(
self,
@@ -59,6 +67,11 @@ class WordPressCLI:
"--",
*command,
)
timeout = COMMAND_TIMEOUT
if self.deadline is not None:
timeout = min(timeout, self.deadline - monotonic())
if timeout <= 0:
raise subprocess.TimeoutExpired(command, timeout)
with TemporaryFile() as output:
result = subprocess.run(
command,
@@ -78,7 +91,7 @@ class WordPressCLI:
group=self.gid,
extra_groups=[],
umask=0o027,
timeout=COMMAND_TIMEOUT,
timeout=timeout,
check=False,
)
if read:
@@ -274,6 +287,7 @@ def wordpress_install(request, cli, public, uid, web_gid):
def apply_wordpress_request(request):
deadline = monotonic() + 165
if os.geteuid() != 0:
raise ValueError("Run WordPress operations on the web node.")
try:
@@ -283,7 +297,7 @@ def apply_wordpress_request(request):
"Install the verified WP-CLI launcher on the web node."
) from None
if (
request.action != "inspect"
request.action not in ("inspect", "check-updates")
and https_status(request.site)["state"] != "configured"
):
raise ValueError("Set up HTTPS for this website first.")
@@ -300,7 +314,7 @@ def apply_wordpress_request(request):
with TemporaryDirectory(prefix="coulobre-wp-cli-") as working:
home = Path(working)
os.chown(home, uid, user.pw_gid)
cli = WordPressCLI(runtime, home, uid, user.pw_gid)
cli = WordPressCLI(runtime, home, uid, user.pw_gid, deadline)
try:
return apply_site_operation(request, cli, public, uid, web_gid)
except subprocess.TimeoutExpired:
@@ -308,8 +322,28 @@ def apply_wordpress_request(request):
def apply_site_operation(request, cli, public, uid, web_gid):
if request.action == "inspect":
return {"wp_version": wordpress_version(cli, public)}
if request.action in ("inspect", "check-updates", "update"):
version = wordpress_version(cli, public)
report = {"wp_version": version}
if request.action == "check-updates":
report["updates"] = [
update.manifest()
for update in update_inventory(cli, public, version)
]
report["database_name"] = (
database_name(cli, public) if version else ""
)
validate_update_inventory(report)
elif request.action == "update":
apply_update(request, cli, public, version)
report["wp_version"] = wordpress_version(cli, public)
if request.update["kind"] == "core" and (
report["wp_version"] != request.update["version"]
):
raise ValueError(
"The updated WordPress version could not be verified."
)
return report
if request.action == "install":
version = wordpress_install(request, cli, public, uid, web_gid)
else:
+176
View File
@@ -0,0 +1,176 @@
import json
import stat
from zipfile import BadZipFile
from .account_backup import open_account_bundle
from .account_backup_request import backup_archive
from .database_node import DEFAULT_SOCKET
from .wordpress_updates import DATABASE_NAME, WordPressUpdate
DATABASE_TARGET = (
"echo wp_json_encode( [ 'name' => DB_NAME, 'host' => DB_HOST, "
"'multisite' => is_multisite() ] );"
)
OFFICIAL_DOWNLOADS = "https://downloads.wordpress.org/"
def database_name(cli, root):
try:
regular_config = stat.S_ISREG((root / "wp-config.php").lstat().st_mode)
except FileNotFoundError:
regular_config = False
if not regular_config:
return ""
data = cli.require(
root,
"identify the WordPress database",
"eval",
DATABASE_TARGET,
read=True,
).stdout
try:
target = json.loads(data)
name = target["name"]
if (
target["host"] in ("localhost", f"localhost:{DEFAULT_SOCKET}")
and target["multisite"] is False
and isinstance(name, str)
and DATABASE_NAME.fullmatch(name)
):
return name
except (ValueError, KeyError, TypeError):
raise ValueError("WP-CLI returned invalid database details.") from None
return ""
def wp_json(cli, root, *arguments):
result = cli.require(
root,
"read the update information",
*arguments,
"--format=json",
read=True,
)
try:
return json.loads(result.stdout)
except ValueError:
raise ValueError(
"WP-CLI returned invalid update information."
) from None
def core_updates(cli, root, installed):
entries = wp_json(
cli, root, "core", "check-update", "--force-check", "--fields=version"
)
return [
WordPressUpdate("core", "wordpress", installed, entry["version"])
for entry in entries
]
def extension_updates(cli, root, kind):
entries = wp_json(
cli,
root,
kind,
"list",
"--fields=name,version,update_version,update_package",
"--update=available",
)
updates = []
for entry in entries:
slug = entry["name"]
target = entry["update_version"]
package = entry["update_package"]
directory = "plugin" if kind == "plugin" else "theme"
if package != f"{OFFICIAL_DOWNLOADS}{directory}/{slug}.{target}.zip":
continue
try:
updates.append(
WordPressUpdate(kind, slug, entry["version"], target)
)
except ValueError:
continue
return updates
def update_inventory(cli, root, installed, kind=None):
if not installed:
return []
try:
updates = (
core_updates(cli, root, installed)
if kind in (None, "core")
else []
)
for extension in ("plugin", "theme"):
if kind in (None, extension):
updates.extend(extension_updates(cli, root, extension))
except (KeyError, TypeError):
raise ValueError(
"WP-CLI returned invalid update information."
) from None
return updates
def verify_recovery_archive(request):
archive = backup_archive(request.site.account_id, request.backup_id)
try:
with open_account_bundle(archive) as (bundle, backup):
resources = {
resource
for resource, _, filename in backup.components()
if bundle.getinfo(filename).file_size
}
except (FileNotFoundError, BadZipFile, KeyError, ValueError):
raise ValueError(
"The WordPress recovery archive is unavailable."
) from None
if resources != {request.site, request.database}:
raise ValueError(
"The recovery archive must include this site and database."
)
def apply_update(request, cli, root, installed):
update = WordPressUpdate.from_manifest(request.update)
verify_recovery_archive(request)
if database_name(cli, root) != request.database.name:
raise ValueError(
"The WordPress database changed or is no longer local."
)
if update not in update_inventory(cli, root, installed, update.kind):
raise ValueError(
"The selected update changed. Check for updates again."
)
version = f"--version={update.version}"
if update.kind == "core":
cli.require(root, "update WordPress core", "core", "update", version)
cli.require(root, "update the WordPress database", "core", "update-db")
return
cli.require(
root,
f"update the {update.kind}",
update.kind,
"update",
update.slug,
version,
)
result = cli.require(
root,
f"verify the {update.kind} version",
update.kind,
"get",
update.slug,
"--field=version",
read=True,
)
if (
result.stdout.decode("ascii", errors="replace").strip()
!= update.version
):
raise ValueError(
"The updated component version could not be verified."
)
+63
View File
@@ -0,0 +1,63 @@
import re
from dataclasses import asdict, dataclass
from .wordpress import LOGIN, VERSION
RELEASE = re.compile(r"[0-9]+(?:\.[0-9]+){0,5}", re.ASCII)
DATABASE_NAME = re.compile(r"[a-z0-9_]{1,55}", re.ASCII)
KINDS = ("core", "plugin", "theme")
@dataclass(frozen=True)
class WordPressUpdate:
kind: str
slug: str
installed: str
version: str
def __post_init__(self):
if (
self.kind not in KINDS
or not isinstance(self.slug, str)
or not LOGIN.fullmatch(self.slug)
or (self.kind == "core" and self.slug != "wordpress")
or not isinstance(self.installed, str)
or not VERSION.fullmatch(self.installed)
or not isinstance(self.version, str)
or len(self.version) > 30
or not RELEASE.fullmatch(self.version)
or self.installed == self.version
):
raise ValueError("Invalid WordPress update selection.")
@classmethod
def from_manifest(cls, data):
if not isinstance(data, dict) or data.keys() != {
"kind",
"slug",
"installed",
"version",
}:
raise ValueError("Invalid WordPress update selection.")
return cls(**data)
def manifest(self):
return asdict(self)
def validate_update_inventory(reply):
database = reply.get("database_name", "")
updates = reply.get("updates")
if (
not isinstance(database, str)
or (database and not DATABASE_NAME.fullmatch(database))
or not isinstance(updates, list)
or len(updates) > 120
):
raise ValueError("The web node returned an invalid update inventory.")
entries = [WordPressUpdate.from_manifest(item) for item in updates]
if len(
{(entry.kind, entry.slug, entry.version) for entry in entries}
) != len(entries):
raise ValueError("The web node returned duplicate WordPress updates.")
return {"database_name": database, "updates": updates}