diff --git a/docs/deployment.md b/docs/deployment.md index 9d1013e..9f99f87 100644 --- a/docs/deployment.md +++ b/docs/deployment.md @@ -1441,6 +1441,23 @@ 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. +### Refresh private WordPress staging from the panel + +For panel-managed staging, use `staging.`. Before the +first refresh, the operator sets up the DNS, HTTPS certificate and Apache +password file as described below. On the site's WordPress page, select +its managed live database, confirm the replacement and choose **Refresh +from live**. If the candidate cannot be verified or published, the +previous staging revision remains available. + +Check for updates on the WordPress page and use **Test on staging** to +apply a selected WordPress.org update to the current staging revision. +The web node downloads the package from WordPress.org and applies it with +network access and outbound mail still blocked for staging. The +installed component must match the one in the update selection. To undo +an unsuccessful test, refresh staging from live. Testing an update does +not modify or promote the live site. + ### Prepare a private WordPress staging revision on a web node The web-node CLI can build an unpublished staging revision for a diff --git a/src/coulobre/hosting/wordpress_management.py b/src/coulobre/hosting/wordpress_management.py index f5e3df9..5da2394 100644 --- a/src/coulobre/hosting/wordpress_management.py +++ b/src/coulobre/hosting/wordpress_management.py @@ -1,5 +1,6 @@ from datetime import timedelta from secrets import token_hex +from uuid import uuid4 from django.conf import settings from django.core.exceptions import PermissionDenied, ValidationError @@ -9,6 +10,11 @@ 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_staging import ( + WordPressStagingRefresh, + WordPressStagingRevision, + WordPressStagingUpdate, +) from coulobre.wordpress_updates import validate_update_inventory from .access import customer_for_user, manages_account, reseller_for_user @@ -103,6 +109,21 @@ def update_database(account, name): ) +def wordpress_staging_databases(account): + return account.databases.filter( + provisioning__finished_at__isnull=False, + provisioning__problem="", + ).order_by("pk") + + +def published_staging(jobs): + return ( + jobs.filter(action="stage", finished_at__isnull=False, problem="") + .order_by("-pk") + .first() + ) + + def prepare_update_recovery(account, site, actor, jobs, selection): if not can_recover_updates(): raise ValidationError( @@ -193,6 +214,54 @@ def queue_wordpress_job(account, site, actor, action, details): database, backup = prepare_update_recovery( account, site, actor, jobs, details.get("update") ) + elif action == "stage": + database = ( + wordpress_staging_databases(account) + .filter(pk=details.get("database_id")) + .first() + ) + if database is None: + raise ValidationError( + "Select a provisioned database for this site." + ) + try: + candidate = WordPressStagingRevision( + site, database.spec, f"staging.{site.domain}", uuid4() + ) + request = WordPressStagingRefresh(candidate) + except ValueError as error: + raise ValidationError(str(error)) from error + return WordPressJob.objects.create( + account=account, + site=site.manifest(), + actor=actor, + actor_role=role, + action=action, + details=request.manifest(), + database=database, + ) + elif action == "stage-update": + selection = details.get("update") + if selection not in current_update_inventory(jobs).get("updates", ()): + raise ValidationError("Check for WordPress.org updates again.") + stage_job = published_staging(jobs) + if stage_job is None: + raise ValidationError("Refresh the live site into staging first.") + try: + candidate = WordPressStagingRefresh.from_manifest( + stage_job.details + ).candidate + request = WordPressStagingUpdate(candidate, selection) + except ValueError as error: + raise ValidationError(str(error)) from error + return WordPressJob.objects.create( + account=account, + site=site.manifest(), + actor=actor, + actor_role=role, + action=action, + details=request.manifest(), + ) request_details = details.copy() if backup is not None: request_details["backup_id"] = str(backup.backup_id) @@ -234,12 +303,51 @@ 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 in ("install", "update") and ( + if job.action in ("install", "update", "stage") and ( database is None or database.account_id != account.pk or database.provisioning.state != "configured" ): raise ValueError("The WordPress database is not ready.") + if job.action in ("stage", "stage-update"): + if job.action == "stage": + request = WordPressStagingRefresh.from_manifest(job.details) + candidate = request.candidate + if candidate.source_database != database.spec: + raise ValueError("The staging request uses another database.") + else: + request = WordPressStagingUpdate.from_manifest(job.details) + candidate = request.staging + if candidate.site != site: + raise ValueError( + "The staging request does not match the live site." + ) + reply = apply_on_local_node( + request, + "/run/coulobre-web-apply.sock", + "web node", + "WordPress staging operation", + timeout=175, + ) + version = reply.get("wp_version") + cleanup_pending = reply.get("cleanup_pending", False) + if ( + reply.get("staging_domain") != candidate.domain + or reply.get("staging_revision") != str(candidate.revision) + or not isinstance(version, str) + or not VERSION.fullmatch(version) + or type(cleanup_pending) is not bool + ): + raise ValueError( + "The web node returned an invalid staging report." + ) + return { + "report": { + "version": version, + "staging_domain": candidate.domain, + "cleanup_pending": cleanup_pending, + } + } details = job.details.copy() if job.action == "update": backup = job.backup diff --git a/src/coulobre/web_node.py b/src/coulobre/web_node.py index 037a1cf..b1d9995 100644 --- a/src/coulobre/web_node.py +++ b/src/coulobre/web_node.py @@ -262,9 +262,19 @@ class WebPhpRequest: def parse_web_request(data): from .wordpress import OPERATION, WordPressRequest + from .wordpress_staging import ( + REFRESH_OPERATION, + UPDATE_OPERATION, + WordPressStagingRefresh, + WordPressStagingUpdate, + ) if isinstance(data, dict) and data.get("operation") == OPERATION: return WordPressRequest.from_manifest(data) + if isinstance(data, dict) and data.get("operation") == REFRESH_OPERATION: + return WordPressStagingRefresh.from_manifest(data) + if isinstance(data, dict) and data.get("operation") == UPDATE_OPERATION: + return WordPressStagingUpdate.from_manifest(data) if ( isinstance(data, dict) and data.get("operation") == "set_website_redirects" @@ -379,11 +389,23 @@ class WebPhpVersionRequest: def apply_web_request(request): from .web_redirects import RedirectConfiguration from .wordpress import WordPressRequest + from .wordpress_staging import ( + WordPressStagingRefresh, + WordPressStagingUpdate, + ) if isinstance(request, WordPressRequest): from .wordpress_node import apply_wordpress_request return apply_wordpress_request(request) + if isinstance(request, WordPressStagingRefresh): + from .wordpress_staging_publication import refresh_staging + + return refresh_staging(request.candidate) + if isinstance(request, WordPressStagingUpdate): + from .wordpress_staging_updates import update_staging + + return update_staging(request) if isinstance(request, RedirectConfiguration): from .web_node_redirects import apply_redirects diff --git a/src/coulobre/wordpress_staging.py b/src/coulobre/wordpress_staging.py index 486a956..1ac6b0e 100644 --- a/src/coulobre/wordpress_staging.py +++ b/src/coulobre/wordpress_staging.py @@ -6,6 +6,8 @@ from .database_node import DatabaseSpec from .web_node import WebSite TABLE_PREFIX = re.compile(r"[A-Za-z0-9_]{1,48}", re.ASCII) +REFRESH_OPERATION = "refresh_wordpress_staging" +UPDATE_OPERATION = "update_wordpress_staging" @dataclass(frozen=True) @@ -78,3 +80,58 @@ def validate_table_prefix(value): "WordPress must use a supported literal table prefix." ) return value + + +@dataclass(frozen=True) +class WordPressStagingRefresh: + candidate: WordPressStagingRevision + + def __post_init__(self): + if self.candidate.domain != f"staging.{self.candidate.site.domain}": + raise ValueError("Panel staging uses staging..") + + def manifest(self): + return { + "operation": REFRESH_OPERATION, + "candidate": self.candidate.manifest(), + } + + @classmethod + def from_manifest(cls, data): + if ( + data.keys() != {"operation", "candidate"} + or data["operation"] != REFRESH_OPERATION + ): + raise ValueError("Expected a WordPress staging refresh request.") + return cls(WordPressStagingRevision.from_manifest(data["candidate"])) + + +@dataclass(frozen=True) +class WordPressStagingUpdate: + staging: WordPressStagingRevision + update: dict + + def __post_init__(self): + from .wordpress_updates import WordPressUpdate + + WordPressStagingRefresh(self.staging) + WordPressUpdate.from_manifest(self.update) + + def manifest(self): + return { + "operation": UPDATE_OPERATION, + "staging": self.staging.manifest(), + "update": self.update, + } + + @classmethod + def from_manifest(cls, data): + if ( + data.keys() != {"operation", "staging", "update"} + or data["operation"] != UPDATE_OPERATION + ): + raise ValueError("Expected a WordPress staging update request.") + return cls( + WordPressStagingRevision.from_manifest(data["staging"]), + data["update"], + ) diff --git a/src/coulobre/wordpress_staging_publication.py b/src/coulobre/wordpress_staging_publication.py index d557355..4dc0ac1 100644 --- a/src/coulobre/wordpress_staging_publication.py +++ b/src/coulobre/wordpress_staging_publication.py @@ -37,6 +37,8 @@ from .wordpress_staging_node import ( ISOLATION, STAGING_DIRECTORY, check_revision_request, + discard_staging_revision, + prepare_staging_revision, ) SYSTEMD_DIRECTORY = Path("/etc/systemd/system") @@ -444,3 +446,34 @@ def unpublish_staging_revision(request): "Choose the currently published staging revision." ) apply_vhost(apache, enabled, None) + + +def refresh_staging(request): + # Check operator-managed prerequisites before copying the live data. + access_file(request) + staging_tls_files(request) + previous = read_publication(vhost_paths(request.site)[0]) + if previous is None: + check_initial_hostname(request) + elif previous.domain != request.domain: + raise ValueError("The live site already has another staging hostname.") + try: + report = prepare_staging_revision(request) + published = publish_staging_revision(request) + except (OSError, ValueError) as error: + if not isinstance(error, StagingRollbackError): + with suppress(OSError, ValueError): + discard_staging_revision(request) + raise + cleanup_pending = False + if previous is not None and previous != request: + try: + discard_staging_revision(previous) + except (OSError, ValueError): + cleanup_pending = True + return { + "staging_domain": published["domain"], + "staging_revision": published["revision"], + "wp_version": report["wordpress_version"], + "cleanup_pending": cleanup_pending, + } diff --git a/src/coulobre/wordpress_staging_updates.py b/src/coulobre/wordpress_staging_updates.py new file mode 100644 index 0000000..a750a9f --- /dev/null +++ b/src/coulobre/wordpress_staging_updates.py @@ -0,0 +1,154 @@ +import json +import os +from tempfile import NamedTemporaryFile +from time import monotonic +from urllib.error import URLError +from urllib.request import HTTPRedirectHandler, ProxyHandler, build_opener + +from . import web_node_apply as web +from .node_files import ( + locked_root_directory, + read_root_file, + require_root_directory, +) +from .wordpress_node import wordpress_version +from .wordpress_staging_node import ( + STAGING_DIRECTORY, + IsolatedWordPressCLI, + check_revision_request, + read_option, +) +from .wordpress_staging_publication import read_publication, vhost_paths +from .wordpress_updates import WordPressUpdate + +DOWNLOAD_HOST = "https://downloads.wordpress.org/" +MAX_DOWNLOAD_BYTES = 100 * 1024**2 + + +class NoRedirects(HTTPRedirectHandler): + def redirect_request(self, *args, **kwargs): + return None + + +def package_url(update): + if update.kind == "core": + return ( + f"{DOWNLOAD_HOST}release/wordpress-{update.version}-no-content.zip" + ) + return f"{DOWNLOAD_HOST}{update.kind}/{update.slug}.{update.version}.zip" + + +def download_update(update, target): + opener = build_opener(ProxyHandler({}), NoRedirects()) + deadline = monotonic() + 35 + total = 0 + try: + with opener.open(package_url(update), timeout=12) as outgoing: + while True: + data = outgoing.read(256 * 1024) + if not data: + break + total += len(data) + if total > MAX_DOWNLOAD_BYTES or monotonic() > deadline: + raise ValueError( + "The WordPress update download exceeded its limits." + ) + target.write(data) + except (OSError, URLError) as error: + raise ValueError( + "Could not download the update from WordPress.org." + ) from error + if not total: + raise ValueError("WordPress.org returned an empty update.") + target.flush() + + +def installed_component(cli, public, update): + if update.kind == "core": + return wordpress_version(cli, public) + return ( + cli.require( + public, + "read the staging component version", + update.kind, + "get", + update.slug, + "--field=version", + read=True, + ) + .stdout.decode("ascii", errors="replace") + .strip() + ) + + +def update_staging(request): + if os.geteuid() != 0: + raise ValueError("Run staging updates on the web node.") + stage = request.staging + update = WordPressUpdate.from_manifest(request.update) + directory = STAGING_DIRECTORY / stage.key + with locked_root_directory(STAGING_DIRECTORY): + if read_publication(vhost_paths(stage.site)[0]) != stage: + raise ValueError("This staging revision is no longer published.") + require_root_directory(directory) + check_revision_request(stage, directory) + report = json.loads( + read_root_file(directory / "revision.json", mode=0o600) + )["report"] + uid, web_gid = web.check_system_account(stage.key, directory) + user = web.current_user(stage.key) + public = directory / "public" + web.check_public_directory(public, uid, web_gid) + cli = IsolatedWordPressCLI( + report["php"], + directory / "cli", + uid, + user.pw_gid, + monotonic() + 150, + ) + if installed_component(cli, public, update) != update.installed: + raise ValueError("This component has changed on staging.") + with NamedTemporaryFile( + dir=directory, prefix="update-", suffix=".zip" + ) as package: + download_update(update, package) + os.fchown(package.fileno(), 0, cli.gid) + os.fchmod(package.fileno(), 0o640) + if update.kind == "core": + cli.require( + public, + "update staging core", + "core", + "update", + package.name, + ) + cli.require( + public, "update the staging database", "core", "update-db" + ) + else: + cli.require( + public, + f"update the staging {update.kind}", + update.kind, + "install", + package.name, + "--force", + ) + if installed_component(cli, public, update) != update.version: + raise ValueError("Could not verify the updated staging component.") + if any( + read_option(cli, public, option) != value + for option, value in ( + ("home", f"https://{stage.domain}"), + ("siteurl", f"https://{stage.domain}"), + ("blog_public", "0"), + ) + ): + raise ValueError( + "The updated staging settings could not be verified." + ) + return { + "wp_version": wordpress_version(cli, public), + "staging_domain": stage.domain, + "staging_revision": str(stage.revision), + }