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..ba57994 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()
@@ -319,6 +319,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 +329,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..fbe595f
--- /dev/null
+++ b/src/coulobre/wordpress_staging_publication.py
@@ -0,0 +1,387 @@
+"""Publish a verified staging revision on its isolated web runtime."""
+
+import fcntl
+import json
+import os
+import re
+from contextlib import suppress
+from pathlib import Path
+
+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=(",", ":")
+ )
+ 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"
+ 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):
+ 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")
+ 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 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)
+ except StagingRollbackError:
+ raise
+ except (OSError, ValueError, KeyboardInterrupt):
+ if fresh:
+ 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)