diff --git a/docs/deployment.md b/docs/deployment.md index 7770125..60b2473 100644 --- a/docs/deployment.md +++ b/docs/deployment.md @@ -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 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 The installer enables the file manager, scheduled website jobs and local diff --git a/src/coulobre/database_node_backup.py b/src/coulobre/database_node_backup.py index 1f55332..03787fe 100644 --- a/src/coulobre/database_node_backup.py +++ b/src/coulobre/database_node_backup.py @@ -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: raise ValueError("Run backup-database as root on the MariaDB node.") archive = archive.absolute() @@ -33,6 +33,13 @@ def backup_database(database, socket, archive): with managed_database(database, socket) as (cursor, record, record_path): 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 ( client_options(record, record_path.parent) as options, NamedTemporaryFile(dir=archive.parent) as staged, @@ -45,9 +52,7 @@ def backup_database(database, socket, archive): "--skip-add-drop-table", "--no-tablespaces", "--hex-blob", - "--routines", - "--events", - "--triggers", + *objects, database.name, ) 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): - if os.geteuid() != 0: - 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) + archive = private_source_archive(archive) with TemporaryFile(dir=archive.parent) as validated: read_dump(database, archive, 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): for table, schema in (("TABLES", "TABLE_SCHEMA"), *DEFINER_OBJECTS[2:]): cursor.execute( @@ -265,3 +309,26 @@ def import_dump(command, data): "MariaDB could not complete the restore. " "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 diff --git a/src/coulobre/hosting/test_wordpress_staging.py b/src/coulobre/hosting/test_wordpress_staging.py new file mode 100644 index 0000000..d2689cd --- /dev/null +++ b/src/coulobre/hosting/test_wordpress_staging.py @@ -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_") diff --git a/src/coulobre/web_node.py b/src/coulobre/web_node.py index 8984241..b424efa 100644 --- a/src/coulobre/web_node.py +++ b/src/coulobre/web_node.py @@ -548,6 +548,18 @@ 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.add_parser(name, help=description) + staging.add_argument("manifest", type=Path) args = parser.parse_args(argv) if args.command == "restore-site" and args.replace and args.file is None: parser.error("--replace requires --file.") @@ -633,6 +645,22 @@ 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)) + return 0 site = WebSite.from_manifest(payload) if args.command == "apply": from .web_node_apply import apply_site_with_runtime diff --git a/src/coulobre/wordpress_node.py b/src/coulobre/wordpress_node.py index eb3f738..72fbb93 100644 --- a/src/coulobre/wordpress_node.py +++ b/src/coulobre/wordpress_node.py @@ -52,6 +52,7 @@ class WordPressCLI: ): command = ( f"/usr/bin/php{self.runtime}", + *self.php_arguments(), str(WP_CLI), f"--path={root}", "--skip-packages", @@ -73,32 +74,47 @@ class WordPressCLI: if timeout <= 0: raise subprocess.TimeoutExpired(command, timeout) with TemporaryFile() as output: - result = subprocess.run( + result = self.execute( command, - input=data, - stdin=subprocess.DEVNULL if data is None else None, + data=data, stdout=output if read else subprocess.DEVNULL, - stderr=subprocess.DEVNULL, - 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, + login=login, timeout=timeout, - check=False, ) if read: output.seek(0) result.stdout = output.read(REPORT_LIMIT) 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): result = self.run(root, *arguments, **kwargs) if result.returncode: diff --git a/src/coulobre/wordpress_staging.py b/src/coulobre/wordpress_staging.py new file mode 100644 index 0000000..486a956 --- /dev/null +++ b/src/coulobre/wordpress_staging.py @@ -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 diff --git a/src/coulobre/wordpress_staging_node.py b/src/coulobre/wordpress_staging_node.py new file mode 100644 index 0000000..95083ac --- /dev/null +++ b/src/coulobre/wordpress_staging_node.py @@ -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", + "