From d0671fdc2bba97dffb1c4125b135f597f5dc173d Mon Sep 17 00:00:00 2001 From: Peter van Arkel Date: Wed, 2 Dec 2026 01:56:06 +0100 Subject: [PATCH] Verify the active staging HTTPS route before completing publication --- docs/deployment.md | 4 +- .../hosting/test_wordpress_staging.py | 22 ++++++ src/coulobre/wordpress_staging_node.py | 4 +- src/coulobre/wordpress_staging_publication.py | 71 +++++++++++++++++-- 4 files changed, 93 insertions(+), 8 deletions(-) diff --git a/docs/deployment.md b/docs/deployment.md index 312aa88..9d1013e 100644 --- a/docs/deployment.md +++ b/docs/deployment.md @@ -1523,7 +1523,9 @@ 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. You can also publish the previous manifest to switch back. +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 diff --git a/src/coulobre/hosting/test_wordpress_staging.py b/src/coulobre/hosting/test_wordpress_staging.py index 701cdc0..3c4607a 100644 --- a/src/coulobre/hosting/test_wordpress_staging.py +++ b/src/coulobre/hosting/test_wordpress_staging.py @@ -192,3 +192,25 @@ class StagingPublicationTests(SimpleTestCase): 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/wordpress_staging_node.py b/src/coulobre/wordpress_staging_node.py index ba57994..5261b45 100644 --- a/src/coulobre/wordpress_staging_node.py +++ b/src/coulobre/wordpress_staging_node.py @@ -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, diff --git a/src/coulobre/wordpress_staging_publication.py b/src/coulobre/wordpress_staging_publication.py index fbe595f..d557355 100644 --- a/src/coulobre/wordpress_staging_publication.py +++ b/src/coulobre/wordpress_staging_publication.py @@ -4,8 +4,15 @@ 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 ( @@ -131,6 +138,11 @@ def render_vhost(request, directory, credentials, tls): 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} @@ -153,6 +165,7 @@ def render_vhost(request, directory, credentials, tls): 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 @@ -277,7 +290,7 @@ class StagingRollbackError(ValueError): pass -def apply_vhost(apache, enabled, content): +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 @@ -296,6 +309,8 @@ def apply_vhost(apache, enabled, content): 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: @@ -315,6 +330,47 @@ def apply_vhost(apache, enabled, content): 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: @@ -359,11 +415,14 @@ def publish_staging_revision(request): content = render_vhost(request, directory, credentials, tls) fresh = start_runtime(request, directory, runtime) try: - apply_vhost(apache, enabled, content) - except StagingRollbackError: - raise - except (OSError, ValueError, KeyboardInterrupt): - if fresh: + 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