diff --git a/docs/deployment.md b/docs/deployment.md index 60b2473..9d1013e 100644 --- a/docs/deployment.md +++ b/docs/deployment.md @@ -1491,6 +1491,48 @@ its dedicated candidate database. sudo /opt/coulobre/bin/coulobre-web-node discard-wordpress-staging staging.json ``` +### Publish a verified WordPress staging revision over HTTPS + +Choose a separate hostname for staging and point its DNS to the web node. +Obtain a Certbot certificate for the staging hostname. Use the certificate +name `coulobre-wp-staging-NODE_KEY`, with the live website's node key. +Configure the Core Certbot HTTP-01 webroot and Apache reload hook before +using HTTP-01. The staging route keeps that challenge available on port 80 +and redirects other HTTP requests to HTTPS. Enable Apache's `ssl`, +`headers`, `proxy_fcgi` and file-based Basic Authentication modules. + +Create a separate Basic Authentication password for the staging site. +Name the file after the live website's node key, which is the account ID +for a primary site and `s` followed by the site ID for an independent site. +For the primary site of account 17, use these commands. + +```sh +sudo install -d -m 0755 /etc/apache2/coulobre-wordpress-staging +sudo htpasswd -B -c /etc/apache2/coulobre-wordpress-staging/17.htpasswd staging +sudo chown root:www-data /etc/apache2/coulobre-wordpress-staging/17.htpasswd +sudo chmod 0640 /etc/apache2/coulobre-wordpress-staging/17.htpasswd +sudo /opt/coulobre/bin/coulobre-web-node publish-wordpress-staging staging.json +``` + +Omit `-c` when adding or changing users in an existing password file. +The staging site requires authentication for static assets as well as +PHP requests and sends `X-Robots-Tag: noindex, nofollow`. Its separate +PHP-FPM service uses the candidate Unix identity and database. Outbound +IP networking and PHP mail are disabled. + +To refresh, prepare a new revision with the same hostname and publish +its manifest. The same password file stays in use. Coulobre keeps the +previous revision and restores its Apache configuration if the switch +fails. Publication checks the new certificate and authentication challenge +through Apache's local HTTPS listener on `127.0.0.1:443`. You can also +publish the previous manifest to switch back. +Discard unused revisions to remove their databases and PHP-FPM services. + +To withdraw the staging route, run `unpublish-wordpress-staging` with +the manifest of the currently published revision. Remove its DNS record +if you are retiring the hostname. After withdrawing the route, you can +discard the remaining revision through the web-node CLI. + ## Enable the website file manager The installer enables the file manager, scheduled website jobs and local diff --git a/src/coulobre/hosting/test_wordpress_staging.py b/src/coulobre/hosting/test_wordpress_staging.py index d2689cd..3c4607a 100644 --- a/src/coulobre/hosting/test_wordpress_staging.py +++ b/src/coulobre/hosting/test_wordpress_staging.py @@ -1,5 +1,6 @@ from pathlib import Path from subprocess import CompletedProcess +from tempfile import TemporaryDirectory from unittest.mock import Mock, patch from uuid import uuid4 @@ -7,6 +8,7 @@ from django.test import SimpleTestCase from coulobre.database_node import DatabaseSpec from coulobre.database_node_backup import check_wordpress_schema +from coulobre.php_runtime import PhpRuntime from coulobre.web_node import WebSite from coulobre.wordpress_staging import WordPressStagingRevision from coulobre.wordpress_staging_node import ( @@ -14,6 +16,12 @@ from coulobre.wordpress_staging_node import ( read_source_config, verify_stage, ) +from coulobre.wordpress_staging_publication import ( + apply_vhost, + render_pool, + render_runtime, + render_vhost, +) class StagingRevisionTests(SimpleTestCase): @@ -119,3 +127,90 @@ class WordPressSchemaTests(SimpleTestCase): check_wordpress_schema(cursor, "test_db", "wp_") else: check_wordpress_schema(cursor, "test_db", "wp_") + + +class StagingPublicationTests(SimpleTestCase): + def setUp(self): + self.revision = WordPressStagingRevision( + WebSite(7, "wordpress.example.test"), + DatabaseSpec(7, "wordpress"), + "preview.example.test", + uuid4(), + ) + + def test_https_requires_access_for_static_files_and_php(self): + directory = Path("/srv/coulobre/wordpress-staging") / self.revision.key + config = render_vhost( + self.revision, + directory, + Path("/etc/wordpress.htpasswd"), + (Path("/etc/fullchain.pem"), Path("/etc/privkey.pem")), + ) + self.assertIn("ServerName preview.example.test", config) + self.assertIn('RedirectMatch permanent "', config) + self.assertIn("https://preview.example.test/$1", config) + self.assertIn('Alias "/.well-known/acme-challenge/"', config) + self.assertIn('', config) + self.assertIn("Require valid-user", config) + self.assertIn("RequestHeader unset Authorization", config) + self.assertIn( + 'Header always set X-Robots-Tag "noindex, nofollow"', config + ) + self.assertIn( + 'Header always set Cache-Control "private, no-store"', config + ) + self.assertNotIn("wordpress.example.test", config.partition("\n")[2]) + + def test_the_web_runtime_uses_the_staging_identity_and_blocks_egress(self): + directory = Path("/srv/coulobre/wordpress-staging") / self.revision.key + unit = render_runtime(self.revision, directory, PhpRuntime("8.5")) + pool = render_pool(self.revision, directory) + self.assertIn("PrivateNetwork=yes", unit) + self.assertIn("RestrictAddressFamilies=AF_UNIX", unit) + self.assertIn("TemporaryFileSystem=/run:ro", unit) + self.assertIn("BindReadOnlyPaths=/run/mysqld", unit) + self.assertIn(f"user = {self.revision.key}", pool) + self.assertIn("php_admin_value[sendmail_path] = /usr/bin/false", pool) + + @patch("coulobre.wordpress_staging_publication.read_root_file") + @patch("coulobre.wordpress_staging_publication.web.run") + def test_failed_reload_restores_the_previous_route(self, run, read): + read.side_effect = Path.read_text + run.side_effect = (None, ValueError("Apache reload failed"), None) + with TemporaryDirectory() as work: + root = Path(work) + available = root / "sites-available" + enabled = root / "sites-enabled" + available.mkdir() + enabled.mkdir() + config = available / "staging.conf" + link = enabled / config.name + link.symlink_to(Path("../sites-available") / config.name) + config.write_text("previous verified revision") + with self.assertRaisesRegex(ValueError, "Apache reload failed"): + apply_vhost(config, link, "new verified revision") + self.assertEqual(config.read_text(), "previous verified revision") + self.assertTrue(link.exists()) + self.assertEqual(run.call_count, 3) + + @patch("coulobre.wordpress_staging_publication.web.run") + def test_initial_publication_is_removed_when_https_verification_fails( + self, run + ): + verification = Mock(side_effect=ValueError("Staging TLS not active")) + with TemporaryDirectory() as work: + root = Path(work) + apache = root / "sites-available" / "stage.conf" + enabled = root / "sites-enabled" / apache.name + apache.parent.mkdir() + enabled.parent.mkdir() + with self.assertRaisesRegex(ValueError, "Staging TLS not active"): + apply_vhost( + apache, + enabled, + "verified candidate", + verify=verification, + ) + self.assertFalse(apache.exists()) + self.assertFalse(enabled.is_symlink()) + self.assertEqual(run.call_count, 3) diff --git a/src/coulobre/web_node.py b/src/coulobre/web_node.py index b424efa..037a1cf 100644 --- a/src/coulobre/web_node.py +++ b/src/coulobre/web_node.py @@ -548,16 +548,13 @@ def main(argv=None): commands.add_parser( "job-request", help="Run a scheduled job as the website user." ) - for name, description in ( - ( - "prepare-wordpress-staging", - "Prepare a private WordPress staging copy.", - ), - ( - "discard-wordpress-staging", - "Remove an unpublished staging revision.", - ), - ): + staging_commands = { + "prepare-wordpress-staging": "Prepare a private WordPress copy.", + "publish-wordpress-staging": "Publish a verified staging revision.", + "unpublish-wordpress-staging": "Remove the staging HTTPS route.", + "discard-wordpress-staging": "Remove an unpublished staging revision.", + } + for name, description in staging_commands.items(): staging = commands.add_parser(name, help=description) staging.add_argument("manifest", type=Path) args = parser.parse_args(argv) @@ -645,21 +642,8 @@ def main(argv=None): try: payload = json.loads(args.manifest.read_text(encoding="utf-8")) - if args.command in ( - "prepare-wordpress-staging", - "discard-wordpress-staging", - ): - from .wordpress_staging import WordPressStagingRevision - from .wordpress_staging_node import ( - discard_staging_revision, - prepare_staging_revision, - ) - - revision = WordPressStagingRevision.from_manifest(payload) - if args.command == "discard-wordpress-staging": - discard_staging_revision(revision) - else: - print(json.dumps(prepare_staging_revision(revision), indent=2)) + if args.command in staging_commands: + run_staging_command(args.command, payload) return 0 site = WebSite.from_manifest(payload) if args.command == "apply": @@ -736,3 +720,26 @@ def main(argv=None): parser.exit(1, f"coulobre-web-node: {error}\n") return 0 + + +def run_staging_command(command, payload): + from .wordpress_staging import WordPressStagingRevision + from .wordpress_staging_node import ( + discard_staging_revision, + prepare_staging_revision, + ) + from .wordpress_staging_publication import ( + publish_staging_revision, + unpublish_staging_revision, + ) + + actions = { + "prepare-wordpress-staging": prepare_staging_revision, + "publish-wordpress-staging": publish_staging_revision, + "unpublish-wordpress-staging": unpublish_staging_revision, + "discard-wordpress-staging": discard_staging_revision, + } + revision = WordPressStagingRevision.from_manifest(payload) + report = actions[command](revision) + if report is not None: + print(json.dumps(report, indent=2)) diff --git a/src/coulobre/web_node_apply.py b/src/coulobre/web_node_apply.py index d622c7c..d745c06 100644 --- a/src/coulobre/web_node_apply.py +++ b/src/coulobre/web_node_apply.py @@ -295,7 +295,10 @@ def check_services(runtime): def reserve_account(site, user, paths): + from .wordpress_staging_publication import check_staging_hostname_available + reject_tool_hostname(site.domain) + check_staging_hostname_available(site.domain) marker = STATE_DIRECTORY / f"{site.node_key}.json" if os.path.lexists(marker.with_suffix(".retired")): raise ValueError("This website belongs to a retired hosting account.") diff --git a/src/coulobre/wordpress_staging_node.py b/src/coulobre/wordpress_staging_node.py index 95083ac..5261b45 100644 --- a/src/coulobre/wordpress_staging_node.py +++ b/src/coulobre/wordpress_staging_node.py @@ -41,7 +41,6 @@ ISOLATION = ( "BindReadOnlyPaths=/run/mysqld", "InaccessiblePaths=-/srv/coulobre/web -/var/spool -/var/lib/coulobre", "InaccessiblePaths=-/usr/sbin/sendmail -/usr/sbin/postdrop", - "RuntimeMaxSec=35s", "UMask=0027", ) SECRET_KEYS = ( @@ -75,6 +74,7 @@ class IsolatedWordPressCLI(WordPressCLI): f"--working-directory={self.home}", *(f"--property={item}" for item in ISOLATION), f"--property=ReadWritePaths={self.home.parent}", + "--property=RuntimeMaxSec=35s", *( f"--setenv={key}={value}" for key, value in self.environment(login).items() @@ -147,7 +147,9 @@ def write_stage_configuration(directory, gid, credentials, prefix): "define( 'DISABLE_WP_CRON', true );\n" "define( 'AUTOMATIC_UPDATER_DISABLED', true );\n" f"$table_prefix = {php_string(prefix)};\n" - "define( 'ABSPATH', __DIR__ . '/public/' );\n" + "if ( ! defined( 'ABSPATH' ) ) {\n" + " define( 'ABSPATH', __DIR__ . '/public/' );\n" + "}\n" "require_once ABSPATH . 'wp-settings.php';\n", mode=0o640, group=gid, @@ -319,6 +321,8 @@ def check_revision_request(request, directory): def discard_staging_revision(request): + from .wordpress_staging_publication import discard_runtime + if os.geteuid() != 0: raise ValueError("Discard WordPress staging as root on the web node.") directory = STAGING_DIRECTORY / request.key @@ -327,6 +331,7 @@ def discard_staging_revision(request): return require_root_directory(directory) check_revision_request(request, directory) + discard_runtime(request, directory) marker = directory / "database-reserved" if os.path.lexists(marker): drop_candidate_database(request.database, DEFAULT_SOCKET) diff --git a/src/coulobre/wordpress_staging_publication.py b/src/coulobre/wordpress_staging_publication.py new file mode 100644 index 0000000..d557355 --- /dev/null +++ b/src/coulobre/wordpress_staging_publication.py @@ -0,0 +1,446 @@ +"""Publish a verified staging revision on its isolated web runtime.""" + +import fcntl +import json +import os +import re +import socket +import ssl +from contextlib import suppress +from http.client import HTTPException, HTTPResponse +from pathlib import Path +from time import monotonic, sleep + +from cryptography import x509 +from cryptography.hazmat.primitives.serialization import Encoding + +from . import web_node_apply as web +from .node_files import ( + check_root_file, + locked_root_directory, + read_root_file, + replace_configuration, + require_root_directory, +) +from .php_runtime import PhpRuntime +from .web_node_aliases import ( + check_alias_domain_available, + check_apache_hostname_available, +) +from .web_node_tls import ( + ACME_WEBROOT, + CERTBOT_ROOT, + validate_certificate_files, +) +from .wordpress_staging import WordPressStagingRevision +from .wordpress_staging_node import ( + ISOLATION, + STAGING_DIRECTORY, + check_revision_request, +) + +SYSTEMD_DIRECTORY = Path("/etc/systemd/system") +ACCESS_DIRECTORY = Path("/etc/apache2/coulobre-wordpress-staging") +VHOST_PREFIX = "zz-coulobre-wp-staging-" +VHOST_MARKER = "# Coulobre WordPress staging revision " +PASSWORD_ENTRY = re.compile( + r"[A-Za-z0-9._@-]{1,64}:\$2[aby]\$(?:0[5-9]|[12][0-9]|3[01])" + r"\$[./A-Za-z0-9]{53}", + re.ASCII, +) + + +def vhost_paths(site): + name = f"{VHOST_PREFIX}{site.node_key}.conf" + return web.APACHE_AVAILABLE / name, web.APACHE_ENABLED / name + + +def read_publication(path): + if not os.path.lexists(path): + return None + content = read_root_file(path) + line = content.partition("\n")[0] + if not line.startswith(VHOST_MARKER): + raise ValueError("Expected a Coulobre WordPress staging vhost.") + request = WordPressStagingRevision.from_manifest( + json.loads(line.removeprefix(VHOST_MARKER)) + ) + if vhost_paths(request.site)[0] != path: + raise ValueError("The staging vhost belongs to a different website.") + return request + + +def check_staging_hostname_available(domain): + for path in web.APACHE_AVAILABLE.glob(f"{VHOST_PREFIX}*.conf"): + if read_publication(path).domain == domain: + raise ValueError("This hostname belongs to WordPress staging.") + + +def access_file(request): + path = ACCESS_DIRECTORY / f"{request.site.node_key}.htpasswd" + require_root_directory(path.parent) + check_root_file(path, mode=0o640) + group = web.current_group("www-data") + if group is None or path.lstat().st_gid != group.gr_gid: + raise ValueError( + "The staging password file must be in group www-data." + ) + with path.open(encoding="ascii") as credentials: + data = credentials.read(16385) + if len(data) > 16384: + raise ValueError("The staging password file exceeds 16 KiB.") + lines = data.splitlines() + if not lines or any(not PASSWORD_ENTRY.fullmatch(line) for line in lines): + raise ValueError("Create the staging password file with htpasswd -B.") + names = {line.partition(":")[0] for line in lines} + if len(names) != len(lines): + raise ValueError("Enter each staging access username only once.") + try: + web.run( + "/usr/sbin/runuser", + "-u", + "www-data", + "--", + "/usr/bin/test", + "-r", + str(path), + ) + except ValueError: + raise ValueError( + "Apache must be able to read the staging password file." + ) from None + return path + + +def staging_tls_files(request): + # Apache follows the Certbot lineage when the certificate renews. + lineage = ( + CERTBOT_ROOT / "live" / f"coulobre-wp-staging-{request.site.node_key}" + ) + require_root_directory(lineage) + archive = lineage.parent.parent / "archive" / lineage.name + require_root_directory(archive) + files = (lineage / "fullchain.pem", lineage / "privkey.pem") + resolved = tuple(file.resolve(strict=True) for file in files) + if any(path.parent != archive for path in resolved): + raise ValueError( + "The staging certificate must use its Certbot lineage." + ) + validate_certificate_files(request, *resolved) + return files + + +def render_vhost(request, directory, credentials, tls): + certificate, key = tls + public = directory / "public" + socket = directory / "php.sock" + challenge = ACME_WEBROOT / ".well-known" / "acme-challenge" + marker = VHOST_MARKER + json.dumps( + request.manifest(), separators=(",", ":") + ) + probe_condition = "-R '127.0.0.1/32'" + probe_header = ( + f'Header always set X-Coulobre-Staging-Revision "{request.revision}" ' + f'"expr={probe_condition}"' + ) + return f'''{marker} + + ServerName {request.domain} + RedirectMatch permanent "^/(?!\\.well-known/acme-challenge/)(.*)$" "https://{request.domain}/$1" + Alias "/.well-known/acme-challenge/" "{challenge}/" + + Options None + AllowOverride None + Require all granted + + + + ServerName {request.domain} + UseCanonicalName On + DocumentRoot "{public}" + SSLEngine On + SSLProtocol -all +TLSv1.2 +TLSv1.3 + SSLCertificateFile "{certificate}" + SSLCertificateKeyFile "{key}" + ProxyPassInherit Off + Header always set X-Robots-Tag "noindex, nofollow" + Header always set Cache-Control "private, no-store" + {probe_header} + RequestHeader unset Authorization + + Require all denied + + + AllowOverride None + Options None + Require all granted + DirectoryIndex index.php + FallbackResource /index.php + + + AuthMerging And + AuthType Basic + AuthName "WordPress staging" + AuthBasicProvider file + AuthUserFile "{credentials}" + Require valid-user + + + Require all denied + + + SetHandler "proxy:unix:{socket}|fcgi://localhost/" + + +''' + + +def runtime_service(request): + return f"coulobre-wordpress-{request.key}.service" + + +def render_runtime(request, directory, runtime): + config = directory / "php-fpm.conf" + protection = "\n".join(ISOLATION) + startup = f"{runtime.binary} --nodaemonize --force-stderr --fpm-config" + return f"""[Unit] +Description=Coulobre WordPress staging {request.key} +After=mariadb.service +Requires=mariadb.service +ConditionPathExists={directory / "revision.json"} + +[Service] +Type=exec +ExecStart={startup} {config} +{protection} +ReadWritePaths={directory} +Restart=on-failure + +[Install] +WantedBy=multi-user.target +""" + + +def render_pool(request, directory): + return f"""[global] +error_log = /dev/null + +[{request.key}] +user = {request.key} +group = {request.key} +listen = {directory / "php.sock"} +listen.owner = www-data +listen.group = www-data +listen.mode = 0660 +pm = ondemand +pm.max_children = 4 +clear_env = yes +security.limit_extensions = .php +catch_workers_output = yes +php_admin_value[sendmail_path] = /usr/bin/false +""" + + +def start_runtime(request, directory, runtime): + require_root_directory(SYSTEMD_DIRECTORY) + name = runtime_service(request) + unit = SYSTEMD_DIRECTORY / name + config = directory / "php-fpm.conf" + with web.configuration_installation() as (created, _): + web.install_configuration( + config, render_pool(request, directory), created + ) + web.run(runtime.binary, "--test", "--fpm-config", str(config)) + web.install_configuration( + unit, render_runtime(request, directory, runtime), created + ) + web.run("/usr/bin/systemctl", "daemon-reload") + try: + web.run("/usr/bin/systemctl", "enable", "--now", name) + web.wait_for_socket(directory / "php.sock") + except (OSError, ValueError, KeyboardInterrupt): + if unit in created: + web.run("/usr/bin/systemctl", "disable", "--now", name) + raise + return unit in created + + +def stop_runtime(request): + name = runtime_service(request) + unit = SYSTEMD_DIRECTORY / name + if not os.path.lexists(unit): + return + check_root_file(unit) + web.run("/usr/bin/systemctl", "disable", "--now", name) + unit.unlink() + web.run("/usr/bin/systemctl", "daemon-reload") + + +def discard_runtime(request, directory): + apache, _ = vhost_paths(request.site) + if read_publication(apache) == request: + raise ValueError( + "Switch away from the published staging revision first." + ) + if (directory / "php-fpm.conf").exists(): + stop_runtime(request) + + +class StagingRollbackError(ValueError): + pass + + +def apply_vhost(apache, enabled, content, *, verify=None): + previous = read_root_file(apache) if os.path.lexists(apache) else None + enabled_before = os.path.lexists(enabled) + link_target = Path("../sites-available") / apache.name + if enabled_before: + web.check_site_link(enabled, link_target) + reload_started = False + try: + if content is None: + enabled.unlink(missing_ok=True) + apache.unlink(missing_ok=True) + else: + if previous != content: + replace_configuration(apache, content) + if not enabled_before: + enabled.symlink_to(link_target) + web.run("/usr/sbin/apache2ctl", "configtest") + reload_started = True + web.run("/usr/sbin/service", "apache2", "reload") + if verify is not None: + verify() + except (OSError, ValueError, KeyboardInterrupt) as error: + try: + if previous is None: + apache.unlink(missing_ok=True) + elif previous != content: + replace_configuration(apache, previous) + if enabled_before and not os.path.lexists(enabled): + enabled.symlink_to(link_target) + elif not enabled_before: + enabled.unlink(missing_ok=True) + if reload_started: + web.run("/usr/sbin/service", "apache2", "reload") + except (OSError, ValueError) as rollback: + raise StagingRollbackError( + f"{error}\nApache rollback failed: {rollback}" + ) from error + raise + + +def verify_https_route(request, chain): + expected = x509.load_pem_x509_certificates(chain.read_bytes())[0] + certificate = expected.public_bytes(Encoding.DER) + context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT) + # Pin the previously validated Certbot leaf to distinguish the vhost + # from the default Apache site during a graceful reload. + context.check_hostname = False + context.verify_mode = ssl.CERT_NONE + deadline = monotonic() + 15 + probe = ( + f"HEAD / HTTP/1.1\r\nHost: {request.domain}\r\n" + "Connection: close\r\n\r\n" + ).encode("ascii") + while monotonic() < deadline: + try: + with ( + socket.create_connection(("127.0.0.1", 443), timeout=1) as tcp, + context.wrap_socket( + tcp, server_hostname=request.domain + ) as tls, + ): + if tls.getpeercert(binary_form=True) == certificate: + tls.sendall(probe) + with HTTPResponse(tls, method="HEAD") as reply: + reply.begin() + if ( + reply.status == 401 + and reply.getheader("X-Coulobre-Staging-Revision") + == str(request.revision) + and reply.getheader("X-Robots-Tag") + == "noindex, nofollow" + ): + return + except (OSError, HTTPException): + pass + sleep(0.2) + raise ValueError( + "Apache is not serving the verified staging revision on local HTTPS." + ) + + +def check_initial_hostname(request): + for marker in web.STATE_DIRECTORY.glob("*.json"): + if json.loads(read_root_file(marker))["domain"] == request.domain: + raise ValueError("This hostname is reserved by a hosted website.") + check_staging_hostname_available(request.domain) + check_alias_domain_available(request.domain) + check_apache_hostname_available(request.domain) + + +def publish_staging_revision(request): + if os.geteuid() != 0: + raise ValueError("Publish WordPress staging as root on the web node.") + directory = STAGING_DIRECTORY / request.key + with ( + locked_root_directory(STAGING_DIRECTORY), + web.locked_web_node(fcntl.LOCK_EX), + ): + require_root_directory(directory) + check_revision_request(request, directory) + report = json.loads( + read_root_file(directory / "revision.json", mode=0o600) + )["report"] + if report["domain"] != request.domain: + raise ValueError("Verify the staging revision before publishing.") + uid, gid = web.check_system_account(request.key, directory) + web.check_public_directory(directory / "public", uid, gid) + runtime = PhpRuntime(report["php"]) + credentials = access_file(request) + tls = staging_tls_files(request) + apache, enabled = vhost_paths(request.site) + for parent in (apache.parent, enabled.parent): + require_root_directory(parent) + previous = read_publication(apache) + if previous is None: + check_initial_hostname(request) + elif ( + previous.site != request.site or previous.domain != request.domain + ): + raise ValueError( + "Refresh must keep the original staging hostname." + ) + content = render_vhost(request, directory, credentials, tls) + fresh = start_runtime(request, directory, runtime) + try: + apply_vhost( + apache, + enabled, + content, + verify=lambda: verify_https_route(request, tls[0]), + ) + except (OSError, ValueError, KeyboardInterrupt) as error: + if fresh and not isinstance(error, StagingRollbackError): + with suppress(OSError, ValueError): + stop_runtime(request) + raise + return {"domain": request.domain, "revision": str(request.revision)} + + +def unpublish_staging_revision(request): + if os.geteuid() != 0: + raise ValueError( + "Unpublish WordPress staging as root on the web node." + ) + with ( + locked_root_directory(STAGING_DIRECTORY), + web.locked_web_node(fcntl.LOCK_EX), + ): + apache, enabled = vhost_paths(request.site) + if read_publication(apache) != request: + raise ValueError( + "Choose the currently published staging revision." + ) + apply_vhost(apache, enabled, None)