Add scoped WordPress updates and recovery archive checks

This commit is contained in:
parkel committed 2026-12-02 01:25:27 +01:00
1 parent b4e2187bf8
commit 17971db97d
5 files changed
+343 -17

No files matched your search

+23 -7
View File
@@ -21,6 +21,7 @@ BASE_MANIFEST_VERSION = 1
MAIL_MANIFEST_VERSION = 2 MAIL_MANIFEST_VERSION = 2
MULTI_SITE_MANIFEST_VERSION = 3 MULTI_SITE_MANIFEST_VERSION = 3
SELECTIVE_MANIFEST_VERSION = 4 SELECTIVE_MANIFEST_VERSION = 4
INDEPENDENT_ONLY_MANIFEST_VERSION = 5
MANIFEST_KIND = "coulobre_account_backup" MANIFEST_KIND = "coulobre_account_backup"
MANIFEST_NAME = "manifest.json" MANIFEST_NAME = "manifest.json"
MAX_MANIFEST_BYTES = 1024 * 1024 MAX_MANIFEST_BYTES = 1024 * 1024
@@ -36,9 +37,7 @@ class AccountBackup:
include_website: bool = True include_website: bool = True
def __post_init__(self): def __post_init__(self):
if type(self.include_website) is not bool or ( if type(self.include_website) is not bool:
not self.include_website and self.additional_websites
):
raise ValueError("Choose whether to include the account websites.") raise ValueError("Choose whether to include the account websites.")
if self.website.site_id is not None: if self.website.site_id is not None:
raise ValueError( raise ValueError(
@@ -90,7 +89,11 @@ class AccountBackup:
site.manifest() for site in self.additional_websites site.manifest() for site in self.additional_websites
] ]
if not self.include_website: 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 manifest["include_website"] = False
return manifest return manifest
@@ -104,18 +107,29 @@ class AccountBackup:
MAIL_MANIFEST_VERSION, MAIL_MANIFEST_VERSION,
MULTI_SITE_MANIFEST_VERSION, MULTI_SITE_MANIFEST_VERSION,
SELECTIVE_MANIFEST_VERSION, SELECTIVE_MANIFEST_VERSION,
INDEPENDENT_ONLY_MANIFEST_VERSION,
): ):
raise ValueError("Unsupported account backup manifest version.") raise ValueError("Unsupported account backup manifest version.")
fields = {"version", "kind", "website", "databases"} 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") fields.add("additional_websites")
if version == SELECTIVE_MANIFEST_VERSION: if version in (
SELECTIVE_MANIFEST_VERSION,
INDEPENDENT_ONLY_MANIFEST_VERSION,
):
fields.add("include_website") fields.add("include_website")
if data.get("include_website") is not False: if data.get("include_website") is not False:
raise ValueError("Expected a selective account backup.") raise ValueError("Expected a selective account backup.")
if version == MAIL_MANIFEST_VERSION or ( if version == MAIL_MANIFEST_VERSION or (
version 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 and "mailboxes" in data
): ):
fields.add("mailboxes") fields.add("mailboxes")
@@ -133,6 +147,8 @@ class AccountBackup:
raise ValueError( raise ValueError(
"Expected a list of additional website manifests." "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( return cls(
WebSite.from_manifest(data["website"]), WebSite.from_manifest(data["website"]),
tuple( tuple(
+37 -5
View File
@@ -1,5 +1,6 @@
import re import re
from dataclasses import dataclass from dataclasses import dataclass
from uuid import UUID
from django.core.exceptions import ValidationError from django.core.exceptions import ValidationError
from django.core.validators import validate_email from django.core.validators import validate_email
@@ -8,7 +9,7 @@ from .database_node import DatabaseSpec
from .web_node import WebSite from .web_node import WebSite
OPERATION = "manage_wordpress" 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) 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) VERSION = re.compile(r"[0-9][A-Za-z0-9.-]{0,29}", re.ASCII)
@@ -21,15 +22,36 @@ class WordPressRequest:
title: str = "" title: str = ""
username: str = "" username: str = ""
email: str = "" email: str = ""
update: dict | None = None
backup_id: str = ""
def __post_init__(self): def __post_init__(self):
if self.action not in ACTIONS: if self.action not in ACTIONS:
raise ValueError("Choose a WordPress action.") 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( if self.database is not None or any(
(self.title, self.username, self.email) (self.title, self.username, self.email)
): ):
raise ValueError("Inspect only accepts a website.") raise ValueError("This operation only accepts a website.")
return return
if not isinstance(self.username, str) or not LOGIN.fullmatch( if not isinstance(self.username, str) or not LOGIN.fullmatch(
self.username self.username
@@ -70,12 +92,18 @@ class WordPressRequest:
"site": self.site.manifest(), "site": self.site.manifest(),
"action": self.action, "action": self.action,
} }
if self.action != "inspect": if self.action in ("install", "add-admin"):
manifest.update(username=self.username, email=self.email) manifest.update(username=self.username, email=self.email)
if self.action == "install": if self.action == "install":
manifest.update( manifest.update(
database=self.database.manifest(), title=self.title 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 return manifest
@classmethod @classmethod
@@ -88,15 +116,19 @@ class WordPressRequest:
fields.update(("username", "email")) fields.update(("username", "email"))
if action == "install": if action == "install":
fields.update(("database", "title")) fields.update(("database", "title"))
if action == "update":
fields.update(("database", "update", "backup_id"))
if data.keys() != fields: if data.keys() != fields:
raise ValueError("Expected a WordPress request.") raise ValueError("Expected a WordPress request.")
return cls( return cls(
WebSite.from_manifest(data["site"]), WebSite.from_manifest(data["site"]),
action, action,
DatabaseSpec.from_manifest(data["database"]) DatabaseSpec.from_manifest(data["database"])
if action == "install" if action in ("install", "update")
else None, else None,
data.get("title", ""), data.get("title", ""),
data.get("username", ""), data.get("username", ""),
data.get("email", ""), 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 dataclasses import dataclass
from pathlib import Path from pathlib import Path
from tempfile import TemporaryDirectory, TemporaryFile from tempfile import TemporaryDirectory, TemporaryFile
from time import monotonic
from uuid import uuid4 from uuid import uuid4
from . import web_node_apply as web 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_restore import publish_empty_webroot
from .web_node_tls import https_status from .web_node_tls import https_status
from .wordpress import VERSION 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") WP_CLI = Path("/usr/local/bin/wp")
COMMAND_TIMEOUT = 35 COMMAND_TIMEOUT = 35
@@ -32,6 +39,7 @@ class WordPressCLI:
home: Path home: Path
uid: int uid: int
gid: int gid: int
deadline: float | None = None
def run( def run(
self, self,
@@ -59,6 +67,11 @@ class WordPressCLI:
"--", "--",
*command, *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: with TemporaryFile() as output:
result = subprocess.run( result = subprocess.run(
command, command,
@@ -78,7 +91,7 @@ class WordPressCLI:
group=self.gid, group=self.gid,
extra_groups=[], extra_groups=[],
umask=0o027, umask=0o027,
timeout=COMMAND_TIMEOUT, timeout=timeout,
check=False, check=False,
) )
if read: if read:
@@ -274,6 +287,7 @@ def wordpress_install(request, cli, public, uid, web_gid):
def apply_wordpress_request(request): def apply_wordpress_request(request):
deadline = monotonic() + 165
if os.geteuid() != 0: if os.geteuid() != 0:
raise ValueError("Run WordPress operations on the web node.") raise ValueError("Run WordPress operations on the web node.")
try: try:
@@ -283,7 +297,7 @@ def apply_wordpress_request(request):
"Install the verified WP-CLI launcher on the web node." "Install the verified WP-CLI launcher on the web node."
) from None ) from None
if ( if (
request.action != "inspect" request.action not in ("inspect", "check-updates")
and https_status(request.site)["state"] != "configured" and https_status(request.site)["state"] != "configured"
): ):
raise ValueError("Set up HTTPS for this website first.") 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: with TemporaryDirectory(prefix="coulobre-wp-cli-") as working:
home = Path(working) home = Path(working)
os.chown(home, uid, user.pw_gid) 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: try:
return apply_site_operation(request, cli, public, uid, web_gid) return apply_site_operation(request, cli, public, uid, web_gid)
except subprocess.TimeoutExpired: except subprocess.TimeoutExpired:
@@ -308,8 +322,28 @@ def apply_wordpress_request(request):
def apply_site_operation(request, cli, public, uid, web_gid): def apply_site_operation(request, cli, public, uid, web_gid):
if request.action == "inspect": if request.action in ("inspect", "check-updates", "update"):
return {"wp_version": wordpress_version(cli, public)} 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": if request.action == "install":
version = wordpress_install(request, cli, public, uid, web_gid) version = wordpress_install(request, cli, public, uid, web_gid)
else: else:
+181
View File
@@ -0,0 +1,181 @@
import json
import stat
from zipfile import BadZipFile, ZipFile
from .account_backup import MANIFEST_NAME, read_backup_manifest
from .account_backup_request import backup_archive
from .database_node import DEFAULT_SOCKET
from .node_files import check_root_file
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:
check_root_file(archive, mode=0o600)
with ZipFile(archive) as bundle:
with bundle.open(MANIFEST_NAME) as source:
backup = read_backup_manifest(source)
resources = [
resource
for resource, manifest, archive_name in backup.components()
if bundle.getinfo(manifest).file_size
and bundle.getinfo(archive_name).file_size
]
except (FileNotFoundError, BadZipFile, KeyError, ValueError):
raise ValueError(
"The WordPress recovery archive is unavailable."
) from None
if set(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}