Prepare isolated WordPress staging revisions #240

Merged
parkel merged 2 commits from feature/wordpress-staging into main 2026-12-02 01:42:06 +01:00
7 changed files with 745 additions and 26 deletions

No files matched your search

+50
View File
@@ -1441,6 +1441,56 @@ replace the customer's latest SFTP export. Managers can ask the server
operator to restore a backup they requested. Schedule updates during a operator to restore a backup they requested. Schedule updates during a
quiet period because WordPress may briefly display a maintenance page. quiet period because WordPress may briefly display a maintenance page.
### Prepare a private WordPress staging revision on a web node
The web-node CLI can build an unpublished staging revision for a
single-site installation with regular website files and a dedicated
Coulobre-managed local MariaDB database. The source must use a literal table
prefix and have no custom database triggers, routines, events, or views.
The node needs systemd network and mount namespacing, a local MariaDB
Unix socket, and the same PHP CLI series and verified WP-CLI used for
WordPress management.
Use a root-controlled JSON file for the request. Set `site` and
`source_database` to the existing native manifests for the live resources.
Set `domain` to the intended staging hostname and `revision` to a new
UUIDv4. For example, a primary website on account 17 can use this manifest.
```json
{
"site": {"version": 1, "account_id": 17, "domain": "www.example.net"},
"source_database": {
"version": 1,
"kind": "mariadb_database",
"account_id": 17,
"suffix": "wordpress"
},
"domain": "stage.example.net",
"revision": "25ef29ed-ae15-4fbc-9bca-fd5c1f278dae"
}
```
```sh
sudo /opt/coulobre/bin/coulobre-web-node prepare-wordpress-staging staging.json
```
The command creates a new revision with its own local database credentials
and Unix identity under `/srv/coulobre/wordpress-staging`. It copies the
document root, rewrites WordPress URLs, and sets search visibility to
discourage indexing. Verification uses a private network namespace, the
local MariaDB Unix socket and disabled PHP mail. This command prepares the
copy only. Publishing over HTTPS with access controls is a separate step.
Use a fresh revision UUID for each refresh. Existing revisions are left
available while a newer copy is prepared.
To remove an unpublished revision, run the following command using the
same manifest. It removes the revision directory, Unix identity, and
its dedicated candidate database.
```sh
sudo /opt/coulobre/bin/coulobre-web-node discard-wordpress-staging staging.json
```
## Enable the website file manager ## Enable the website file manager
The installer enables the file manager, scheduled website jobs and local The installer enables the file manager, scheduled website jobs and local
+76 -9
View File
@@ -23,7 +23,7 @@ DEFINER_OBJECTS = (
) )
def backup_database(database, socket, archive): def backup_database(database, socket, archive, *, wordpress_prefix=None):
if os.geteuid() != 0: if os.geteuid() != 0:
raise ValueError("Run backup-database as root on the MariaDB node.") raise ValueError("Run backup-database as root on the MariaDB node.")
archive = archive.absolute() archive = archive.absolute()
@@ -33,6 +33,13 @@ def backup_database(database, socket, archive):
with managed_database(database, socket) as (cursor, record, record_path): with managed_database(database, socket) as (cursor, record, record_path):
check_definers(cursor, database.name) check_definers(cursor, database.name)
if wordpress_prefix is not None:
check_wordpress_schema(cursor, database.name, wordpress_prefix)
objects = (
("--routines", "--events", "--triggers")
if wordpress_prefix is None
else ("--skip-routines", "--skip-events", "--skip-triggers")
)
with ( with (
client_options(record, record_path.parent) as options, client_options(record, record_path.parent) as options,
NamedTemporaryFile(dir=archive.parent) as staged, NamedTemporaryFile(dir=archive.parent) as staged,
@@ -45,9 +52,7 @@ def backup_database(database, socket, archive):
"--skip-add-drop-table", "--skip-add-drop-table",
"--no-tablespaces", "--no-tablespaces",
"--hex-blob", "--hex-blob",
"--routines", *objects,
"--events",
"--triggers",
database.name, database.name,
) )
with gzip.GzipFile(fileobj=staged, mode="wb", filename="") as data: with gzip.GzipFile(fileobj=staged, mode="wb", filename="") as data:
@@ -65,11 +70,7 @@ def backup_database(database, socket, archive):
def restore_database(database, socket, archive): def restore_database(database, socket, archive):
if os.geteuid() != 0: archive = private_source_archive(archive)
raise ValueError("Run restore-database as root on the MariaDB node.")
archive = archive.absolute()
require_root_directory(archive.parent)
check_root_file(archive, mode=0o600)
with TemporaryFile(dir=archive.parent) as validated: with TemporaryFile(dir=archive.parent) as validated:
read_dump(database, archive, validated) read_dump(database, archive, validated)
restore_dump(database, socket, validated) restore_dump(database, socket, validated)
@@ -177,6 +178,49 @@ def check_definers(cursor, name):
) )
def check_wordpress_schema(cursor, name, prefix):
from .wordpress_staging import validate_table_prefix
validate_table_prefix(prefix)
cursor.execute(
"SELECT TABLE_NAME, TABLE_TYPE FROM information_schema.TABLES "
"WHERE TABLE_SCHEMA = %s",
(name,),
)
tables = cursor.fetchall()
if (
not tables
or any(kind != "BASE TABLE" for _, kind in tables)
or any(not table.startswith(prefix) for table, _ in tables)
):
raise ValueError(
"Staging requires a dedicated WordPress database "
"with ordinary tables."
)
table_names = {table for table, _ in tables}
if (
not {
prefix + table
for table in ("options", "posts", "users", "usermeta")
}
<= table_names
or {prefix + table for table in ("blogs", "sitemeta", "site")}
& table_names
):
raise ValueError("Staging requires a single WordPress website.")
for table, schema in DEFINER_OBJECTS[1:]:
cursor.execute(
f"SELECT 1 FROM information_schema.{table} "
f"WHERE {schema} = %s LIMIT 1",
(name,),
)
if cursor.fetchone() is not None:
raise ValueError(
"Staging requires a database without triggers, "
"routines or events."
)
def check_empty_database(cursor, name): def check_empty_database(cursor, name):
for table, schema in (("TABLES", "TABLE_SCHEMA"), *DEFINER_OBJECTS[2:]): for table, schema in (("TABLES", "TABLE_SCHEMA"), *DEFINER_OBJECTS[2:]):
cursor.execute( cursor.execute(
@@ -265,3 +309,26 @@ def import_dump(command, data):
"MariaDB could not complete the restore. " "MariaDB could not complete the restore. "
"Inspect the target before retrying." "Inspect the target before retrying."
) )
def clone_database_from_archive(source, destination, socket, archive):
if (
source.account_id != destination.account_id
or source.name == destination.name
):
raise ValueError(
"Choose a separate database owned by the same account."
)
archive = private_source_archive(archive)
with TemporaryFile(dir=archive.parent) as validated:
read_dump(source, archive, validated)
restore_dump(destination, socket, validated)
def private_source_archive(archive):
if os.geteuid() != 0:
raise ValueError("Run database restore as root on the MariaDB node.")
archive = archive.absolute()
require_root_directory(archive.parent)
check_root_file(archive, mode=0o600)
return archive
@@ -0,0 +1,121 @@
from pathlib import Path
from subprocess import CompletedProcess
from unittest.mock import Mock, patch
from uuid import uuid4
from django.test import SimpleTestCase
from coulobre.database_node import DatabaseSpec
from coulobre.database_node_backup import check_wordpress_schema
from coulobre.web_node import WebSite
from coulobre.wordpress_staging import WordPressStagingRevision
from coulobre.wordpress_staging_node import (
php_string,
read_source_config,
verify_stage,
)
class StagingRevisionTests(SimpleTestCase):
def setUp(self):
self.site = WebSite(7, "example.test", 9)
self.database = DatabaseSpec(7, "wordpress")
self.revision = WordPressStagingRevision(
self.site, self.database, "stage.example.test", uuid4()
)
def test_revision_requires_a_distinct_hostname_and_scoped_database(self):
manifest = self.revision.manifest()
self.assertEqual(
self.revision, WordPressStagingRevision.from_manifest(manifest)
)
self.assertNotEqual(self.revision.database, self.database)
self.assertEqual(self.revision.database.account_id, 7)
with self.assertRaisesRegex(ValueError, "separate hostname"):
WordPressStagingRevision.from_manifest(
manifest | {"domain": self.site.domain}
)
with self.assertRaisesRegex(ValueError, "must belong"):
WordPressStagingRevision.from_manifest(
manifest
| {"source_database": DatabaseSpec(8, "wordpress").manifest()}
)
self.assertNotEqual(
self.revision.database,
WordPressStagingRevision(
self.site, self.database, self.revision.domain, uuid4()
).database,
)
@patch("coulobre.wordpress_staging_node.config_value")
def test_source_configuration_must_match_the_local_database(self, config):
root = Path("/candidate")
config.side_effect = (self.database.name, "db.example.test")
with self.assertRaisesRegex(ValueError, "local managed live"):
read_source_config(Mock(), root, self.database)
config.side_effect = (self.database.name, "localhost", "wp_custom_")
self.assertEqual(
read_source_config(Mock(), root, self.database), "wp_custom_"
)
def test_php_configuration_literals_escape_quotes_and_backslashes(self):
self.assertEqual(php_string("a'b\\c"), "'a\\'b\\\\c'")
@patch(
"coulobre.wordpress_staging_node.wordpress_version",
return_value="7.1.5",
)
def test_verification_rewrites_only_the_candidate_site(self, _version):
root = Path("/candidate")
cli = Mock()
cli.require.side_effect = (
CompletedProcess((), 0, stdout=b"https://example.test\n"),
None,
None,
CompletedProcess((), 0, stdout=b"https://stage.example.test\n"),
None,
CompletedProcess((), 0, stdout=b"https://stage.example.test\n"),
None,
CompletedProcess((), 0, stdout=b"0\n"),
)
self.assertEqual(
verify_stage(cli, root, self.revision.domain), "7.1.5"
)
self.assertTrue(
all(call.args[0] == root for call in cli.require.call_args_list)
)
commands = [call.args[2:] for call in cli.require.call_args_list]
self.assertIn(("option", "update", "blog_public", "0"), commands)
self.assertIn(
(
"search-replace",
"https://example.test",
"https://stage.example.test",
"--all-tables-with-prefix",
"--skip-columns=guid",
"--quiet",
),
commands,
)
class WordPressSchemaTests(SimpleTestCase):
def test_database_must_contain_only_tables_for_a_single_site(self):
cursor = Mock()
tables = ["wp_options", "wp_posts", "wp_users", "wp_usermeta"]
for extension, message in (
([], ""),
(["wp_blogs"], "single WordPress website"),
(["unrelated_table"], "dedicated WordPress database"),
):
with self.subTest(extension=extension):
cursor.fetchall.return_value = [
(table, "BASE TABLE") for table in tables + extension
]
cursor.fetchone.return_value = None
if message:
with self.assertRaisesRegex(ValueError, message):
check_wordpress_schema(cursor, "test_db", "wp_")
else:
check_wordpress_schema(cursor, "test_db", "wp_")
+28
View File
@@ -548,6 +548,18 @@ def main(argv=None):
commands.add_parser( commands.add_parser(
"job-request", help="Run a scheduled job as the website user." "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.add_parser(name, help=description)
staging.add_argument("manifest", type=Path)
args = parser.parse_args(argv) args = parser.parse_args(argv)
if args.command == "restore-site" and args.replace and args.file is None: if args.command == "restore-site" and args.replace and args.file is None:
parser.error("--replace requires --file.") parser.error("--replace requires --file.")
@@ -633,6 +645,22 @@ def main(argv=None):
try: try:
payload = json.loads(args.manifest.read_text(encoding="utf-8")) 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))
return 0
site = WebSite.from_manifest(payload) site = WebSite.from_manifest(payload)
if args.command == "apply": if args.command == "apply":
from .web_node_apply import apply_site_with_runtime from .web_node_apply import apply_site_with_runtime
+33 -17
View File
@@ -52,6 +52,7 @@ class WordPressCLI:
): ):
command = ( command = (
f"/usr/bin/php{self.runtime}", f"/usr/bin/php{self.runtime}",
*self.php_arguments(),
str(WP_CLI), str(WP_CLI),
f"--path={root}", f"--path={root}",
"--skip-packages", "--skip-packages",
@@ -73,32 +74,47 @@ class WordPressCLI:
if timeout <= 0: if timeout <= 0:
raise subprocess.TimeoutExpired(command, timeout) raise subprocess.TimeoutExpired(command, timeout)
with TemporaryFile() as output: with TemporaryFile() as output:
result = subprocess.run( result = self.execute(
command, command,
input=data, data=data,
stdin=subprocess.DEVNULL if data is None else None,
stdout=output if read else subprocess.DEVNULL, stdout=output if read else subprocess.DEVNULL,
stderr=subprocess.DEVNULL, login=login,
cwd=self.home,
env={
"PATH": "/usr/local/bin:/usr/bin:/bin",
"HOME": str(self.home),
"WP_CLI_CONFIG_PATH": "/dev/null",
"COULOBRE_WP_LOGIN": login,
"LANG": "C.UTF-8",
},
user=self.uid,
group=self.gid,
extra_groups=[],
umask=0o027,
timeout=timeout, timeout=timeout,
check=False,
) )
if read: if read:
output.seek(0) output.seek(0)
result.stdout = output.read(REPORT_LIMIT) result.stdout = output.read(REPORT_LIMIT)
return result return result
def php_arguments(self):
return ()
def execute(self, command, *, data, stdout, login, timeout):
return subprocess.run(
command,
input=data,
stdin=subprocess.DEVNULL if data is None else None,
stdout=stdout,
stderr=subprocess.DEVNULL,
cwd=self.home,
env=self.environment(login),
user=self.uid,
group=self.gid,
extra_groups=[],
umask=0o027,
timeout=timeout,
check=False,
)
def environment(self, login):
return {
"PATH": "/usr/local/bin:/usr/bin:/bin",
"HOME": str(self.home),
"WP_CLI_CONFIG_PATH": "/dev/null",
"COULOBRE_WP_LOGIN": login,
"LANG": "C.UTF-8",
}
def require(self, root, description, *arguments, **kwargs): def require(self, root, description, *arguments, **kwargs):
result = self.run(root, *arguments, **kwargs) result = self.run(root, *arguments, **kwargs)
if result.returncode: if result.returncode:
+80
View File
@@ -0,0 +1,80 @@
import re
from dataclasses import dataclass
from uuid import UUID
from .database_node import DatabaseSpec
from .web_node import WebSite
TABLE_PREFIX = re.compile(r"[A-Za-z0-9_]{1,48}", re.ASCII)
@dataclass(frozen=True)
class WordPressStagingRevision:
site: WebSite
source_database: DatabaseSpec
domain: str
revision: UUID
def __post_init__(self):
stage = WebSite(self.site.account_id, self.domain)
if stage.domain == self.site.domain:
raise ValueError("Choose a separate hostname for staging.")
if self.source_database.account_id != self.site.account_id:
raise ValueError(
"The live database must belong to this website's account."
)
if not isinstance(self.revision, UUID) or self.revision.version != 4:
raise ValueError("Expected a random staging revision ID.")
if self.source_database.name == self.database.name:
raise ValueError("Staging requires a separate database.")
object.__setattr__(self, "domain", stage.domain)
@property
def key(self):
return "wps-" + self.revision.hex[:20]
@property
def database(self):
return DatabaseSpec(
self.site.account_id, "wps_" + self.revision.hex[:20]
)
def manifest(self):
return {
"site": self.site.manifest(),
"source_database": self.source_database.manifest(),
"domain": self.domain,
"revision": str(self.revision),
}
@classmethod
def from_manifest(cls, data):
if not isinstance(data, dict) or data.keys() != {
"site",
"source_database",
"domain",
"revision",
}:
raise ValueError("Expected a staging revision manifest.")
try:
revision = UUID(data["revision"])
except (ValueError, TypeError, AttributeError):
raise ValueError(
"Expected a random staging revision ID."
) from None
if data["revision"] != str(revision):
raise ValueError("Expected a canonical staging revision ID.")
return cls(
WebSite.from_manifest(data["site"]),
DatabaseSpec.from_manifest(data["source_database"]),
data["domain"],
revision,
)
def validate_table_prefix(value):
if not isinstance(value, str) or not TABLE_PREFIX.fullmatch(value):
raise ValueError(
"WordPress must use a supported literal table prefix."
)
return value
+357
View File
@@ -0,0 +1,357 @@
"""Verify a private WordPress copy outside Apache document roots."""
import json
import os
import subprocess
from pathlib import Path
from secrets import token_hex
from shutil import rmtree
from tempfile import TemporaryDirectory
from urllib.parse import urlsplit
from . import database_node_apply as database_node
from . import web_node_apply as web
from .database_node import DEFAULT_SOCKET
from .database_node_backup import backup_database, clone_database_from_archive
from .node_files import (
check_root_file,
locked_root_directory,
read_root_file,
require_root_directory,
write_new_file,
)
from .service_credentials import read_database_credentials
from .web_node_access import website_suspension_path
from .web_node_backup import backup_website, extract_site_archive
from .wordpress_node import WP_CLI, WordPressCLI, wordpress_version
from .wordpress_staging import validate_table_prefix
STAGING_DIRECTORY = Path("/srv/coulobre/wordpress-staging")
ISOLATION = (
"PrivateNetwork=yes",
"RestrictAddressFamilies=AF_UNIX",
"PrivateTmp=yes",
"PrivateDevices=yes",
"ProtectHome=yes",
"ProtectSystem=strict",
"ProtectProc=invisible",
"NoNewPrivileges=yes",
"RestrictNamespaces=yes",
"TemporaryFileSystem=/run:ro",
"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 = (
"AUTH_KEY",
"SECURE_AUTH_KEY",
"LOGGED_IN_KEY",
"NONCE_KEY",
"AUTH_SALT",
"SECURE_AUTH_SALT",
"LOGGED_IN_SALT",
"NONCE_SALT",
)
DROP_INS = ("advanced-cache.php", "db.php", "object-cache.php", "sunrise.php")
class IsolatedWordPressCLI(WordPressCLI):
def php_arguments(self):
return ("-d", "sendmail_path=/usr/bin/false")
def execute(self, command, *, data, stdout, login, timeout):
return subprocess.run(
(
"/usr/bin/systemd-run",
"--quiet",
"--wait",
"--pipe",
"--collect",
"--service-type=exec",
f"--uid={self.uid}",
f"--gid={self.gid}",
f"--working-directory={self.home}",
*(f"--property={item}" for item in ISOLATION),
f"--property=ReadWritePaths={self.home.parent}",
*(
f"--setenv={key}={value}"
for key, value in self.environment(login).items()
),
"--",
*command,
),
input=data,
stdin=subprocess.DEVNULL if data is None else None,
stdout=stdout,
stderr=subprocess.DEVNULL,
timeout=timeout + 5,
check=False,
)
def config_value(cli, root, key, *, variable=False):
return (
cli.require(
root,
"read the WordPress configuration",
"config",
"get",
key,
"--type=variable" if variable else "--type=constant",
read=True,
)
.stdout.decode("utf-8")
.strip()
)
def read_source_config(cli, root, source_database):
if config_value(cli, root, "DB_NAME") != source_database.name:
raise ValueError("The live website uses a different database.")
if config_value(cli, root, "DB_HOST") not in (
"localhost",
f"localhost:{DEFAULT_SOCKET}",
"127.0.0.1",
):
raise ValueError("Staging requires a local managed live database.")
return validate_table_prefix(
config_value(cli, root, "table_prefix", variable=True)
)
def php_string(value):
return "'" + value.replace("\\", "\\\\").replace("'", "\\'") + "'"
def write_stage_configuration(directory, gid, credentials, prefix):
constants = {
"DB_NAME": credentials["database"],
"DB_USER": credentials["user"],
"DB_PASSWORD": credentials["password"],
"DB_HOST": f"localhost:{credentials['socket']}",
"DB_CHARSET": "utf8mb4",
"DB_COLLATE": "",
"WP_ENVIRONMENT_TYPE": "staging",
**{key: token_hex(32) for key in SECRET_KEYS},
}
source = "\n".join(
f"define( {php_string(key)}, {php_string(value)} );"
for key, value in constants.items()
)
write_new_file(
directory / "wp-config.php",
"<?php\n" + source + "\n"
"define( 'WP_HTTP_BLOCK_EXTERNAL', true );\n"
"define( 'DISABLE_WP_CRON', true );\n"
"define( 'AUTOMATIC_UPDATER_DISABLED', true );\n"
f"$table_prefix = {php_string(prefix)};\n"
"define( 'ABSPATH', __DIR__ . '/public/' );\n"
"require_once ABSPATH . 'wp-settings.php';\n",
mode=0o640,
group=gid,
)
def read_option(cli, public, name):
return (
cli.require(
public,
"read the copied WordPress URL",
"option",
"get",
name,
read=True,
)
.stdout.decode("utf-8")
.strip()
)
def verify_stage(cli, public, domain):
version = wordpress_version(cli, public)
if not version:
raise ValueError("The copied WordPress installation is incomplete.")
url = f"https://{domain}"
home = read_option(cli, public, "home")
if (
urlsplit(home).scheme not in ("http", "https")
or not urlsplit(home).hostname
):
raise ValueError("The live WordPress home URL is invalid.")
if home != url and not home.startswith(url + "/"):
cli.require(
public,
"rewrite live links in the staging database",
"search-replace",
home.rstrip("/"),
url,
"--all-tables-with-prefix",
"--skip-columns=guid",
"--quiet",
)
for option, value in (
("home", url),
("siteurl", url),
("blog_public", "0"),
):
cli.require(
public,
"set staging URL and search visibility",
"option",
"update",
option,
value,
)
if read_option(cli, public, option) != value:
raise ValueError("The staging settings could not be verified.")
return version
def initialize_staging_copy(request, directory):
web.site_storage(request.site)
if os.path.lexists(website_suspension_path(request.site)):
raise ValueError("Resume the live website before preparing staging.")
runtime = web.SitePaths.for_site(request.site).runtime.version
if (
web.current_user(request.key) is not None
or web.current_group(request.key) is not None
):
raise ValueError("The staging identity is already in use.")
uid, www_gid = web.ensure_system_account(request.key, directory)
(directory / "user-created").touch(mode=0o600)
account = web.current_user(request.key)
if account is None or uid == 0:
raise ValueError("The staging user is unavailable.")
gid = account.pw_gid
home = directory / "cli"
home.mkdir(mode=0o700)
os.chown(home, uid, gid)
cli = IsolatedWordPressCLI(runtime, home, uid, gid)
public = directory / "public"
with TemporaryDirectory(dir=STAGING_DIRECTORY, prefix=".capture-") as work:
snapshot = Path(work)
files = snapshot / "website.tar.gz"
report = backup_website(request.site, files)
if report["skipped_non_regular_entries"]:
raise ValueError(
"Staging requires regular website files and directories."
)
try:
extract_site_archive(
request.site, files, public, None, uid, www_gid
)
prefix = read_source_config(cli, public, request.source_database)
finally:
(public / "wp-config.php").unlink(missing_ok=True)
for name in DROP_INS:
(public / "wp-content" / name).unlink(missing_ok=True)
dump = snapshot / "database.sql.gz"
backup_database(
request.source_database,
DEFAULT_SOCKET,
dump,
wordpress_prefix=prefix,
)
status = database_node.database_status(
request.database, DEFAULT_SOCKET
)
if status["state"] != "not_installed":
raise ValueError("The staging database name is already in use.")
(directory / "database-reserved").touch(mode=0o600)
database_node.apply_database(request.database, DEFAULT_SOCKET)
clone_database_from_archive(
request.source_database, request.database, DEFAULT_SOCKET, dump
)
write_stage_configuration(
directory, gid, read_database_credentials(request.database), prefix
)
version = verify_stage(cli, public, request.domain)
return {
"domain": request.domain,
"wordpress_version": version,
"php": runtime,
}
def prepare_staging_revision(request):
if os.geteuid() != 0:
raise ValueError("Prepare WordPress staging as root on the web node.")
check_root_file(WP_CLI)
require_root_directory(STAGING_DIRECTORY.parent)
require_root_directory(STAGING_DIRECTORY, create_mode=0o711)
directory = STAGING_DIRECTORY / request.key
with locked_root_directory(STAGING_DIRECTORY):
marker = directory / "revision.json"
if os.path.lexists(directory):
require_root_directory(directory)
if not os.path.lexists(marker):
raise ValueError(
"Use a new revision after failed preparation."
)
record = json.loads(read_root_file(marker, mode=0o600))
check_revision_request(request, directory)
return record["report"]
directory.mkdir(mode=0o711)
directory.chmod(0o711)
write_new_file(
directory / "request.json",
json.dumps(request.manifest()) + "\n",
mode=0o600,
)
try:
report = initialize_staging_copy(request, directory)
except subprocess.TimeoutExpired:
raise ValueError("Staging verification timed out.") from None
write_new_file(
marker,
json.dumps({"report": report}) + "\n",
mode=0o600,
)
return report
def check_revision_request(request, directory):
saved = json.loads(read_root_file(directory / "request.json", mode=0o600))
if saved != request.manifest():
raise ValueError("This staging revision has a different identity.")
def discard_staging_revision(request):
if os.geteuid() != 0:
raise ValueError("Discard WordPress staging as root on the web node.")
directory = STAGING_DIRECTORY / request.key
with locked_root_directory(STAGING_DIRECTORY):
if not os.path.lexists(directory):
return
require_root_directory(directory)
check_revision_request(request, directory)
marker = directory / "database-reserved"
if os.path.lexists(marker):
drop_candidate_database(request.database, DEFAULT_SOCKET)
marker.unlink()
marker = directory / "user-created"
if os.path.lexists(marker):
if web.current_user(request.key) is not None:
web.check_system_account(request.key, directory)
web.run("/usr/sbin/userdel", request.key)
if web.current_group(request.key) is not None:
web.run("/usr/sbin/groupdel", request.key)
rmtree(directory)
def drop_candidate_database(database, socket):
socket = socket.resolve()
name = database.name
path = database_node.STATE_DIRECTORY / f"{name}.json"
with database_node.locked_cursor(database, socket) as (driver, cursor):
record = database_node.checked_credentials(
driver, cursor, database, socket, path, restoring=True
)
if record is None:
return
cursor.execute(f"DROP DATABASE `{name}`")
cursor.execute("DROP USER %s@'localhost'", (name,))
for suffix in (".ready", ".restore-pending", ".json"):
path.with_suffix(suffix).unlink(missing_ok=True)