import fcntl import json import os import stat import subprocess from dataclasses import dataclass from pathlib import Path from tempfile import TemporaryDirectory, TemporaryFile from time import monotonic from uuid import uuid4 from . import web_node_apply as web from .node_files import check_root_file from .service_credentials import read_database_credentials from .web_node_access import website_suspension_path from .web_node_files import rename_entry from .web_node_restore import publish_empty_webroot from .web_node_tls import https_status from .wordpress import VERSION from .wordpress_node_updates import ( apply_update, database_name, update_inventory, ) from .wordpress_updates import validate_update_inventory WP_CLI = Path("/usr/local/bin/wp") COMMAND_TIMEOUT = 35 REPORT_LIMIT = 65536 SEND_SETUP_LINK = ( "exit( is_wp_error( retrieve_password( getenv( 'COULOBRE_WP_LOGIN' ) ) ) " "? 1 : 0 );" ) @dataclass(frozen=True) class WordPressCLI: runtime: str home: Path uid: int gid: int deadline: float | None = None def run( self, root, *arguments, data=None, login="", read=False, load_plugins=False, ): command = ( f"/usr/bin/php{self.runtime}", *self.php_arguments(), str(WP_CLI), f"--path={root}", "--skip-packages", "--skip-themes", *(() if load_plugins else ("--skip-plugins",)), "--no-color", *arguments, ) if read: command = ( "/usr/bin/prlimit", f"--fsize={REPORT_LIMIT}:{REPORT_LIMIT}", "--", *command, ) timeout = COMMAND_TIMEOUT if self.deadline is not None: timeout = min(timeout, self.deadline - monotonic()) if timeout <= 0: raise subprocess.TimeoutExpired(command, timeout) with TemporaryFile() as output: result = self.execute( command, data=data, stdout=output if read else subprocess.DEVNULL, login=login, timeout=timeout, ) 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: raise ValueError(f"WP-CLI could not {description}.") return result def wordpress_version(cli, root): if not (root / "wp-includes" / "version.php").is_file(): return "" version = ( cli.require( root, "read the WordPress version", "core", "version", read=True ) .stdout.decode("ascii", errors="replace") .strip() ) if not VERSION.fullmatch(version): raise ValueError("WP-CLI returned an invalid WordPress version.") cli.require( root, "verify the WordPress installation", "core", "is-installed" ) return version def is_starter_page(index): try: descriptor = os.open( index, os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK ) except OSError: return False with os.fdopen(descriptor, "rb") as page: return stat.S_ISREG(os.fstat(page.fileno()).st_mode) and page.read( len(web.STARTER_PAGE) + 1 ) == web.STARTER_PAGE.encode("utf-8") def check_install_target(public): entries = os.listdir(public) if entries and ( entries != ["index.html"] or not is_starter_page(public / "index.html") ): raise ValueError( "Use an empty website or the original Coulobre starter page." ) def publish_wordpress(staged, public): check_install_target(public) index = public / "index.html" if not os.path.lexists(index): publish_empty_webroot(staged, public) return # Keep the actual file until the atomic rename has succeeded. saved = staged.parent / "previous-index" os.replace(index, saved) try: if not is_starter_page(saved): raise ValueError("The starter page changed during setup.") publish_empty_webroot(staged, public) except (OSError, ValueError, KeyboardInterrupt): if not staged.exists(): raise folder = os.open(public.parent, os.O_RDONLY | os.O_DIRECTORY) try: rename_entry( folder, saved.relative_to(public.parent), index.relative_to(public.parent), ) except (OSError, ValueError): recovery = public.parent / f".wordpress-recovery-{uuid4().hex}" os.replace(saved, recovery) raise ValueError( "The document root changed. " f"The previous index is saved at {recovery}." ) from None finally: os.close(folder) raise def open_installation(request, cli, public, uid, web_gid): credentials = read_database_credentials(request.database) with TemporaryDirectory(dir=public.parent, prefix=".wordpress-") as work: parent = Path(work) parent.chmod(0o711) staged = parent / "public" staged.mkdir(mode=0o750) os.chown(staged, uid, web_gid) staged.chmod(0o2750) cli.require(staged, "download WordPress", "core", "download") cli.require(staged, "verify the download", "core", "verify-checksums") cli.require( staged, "configure the managed database", "config", "create", f"--dbname={credentials['database']}", f"--dbuser={credentials['user']}", f"--dbhost=localhost:{credentials['socket']}", "--prompt=dbpass", data=(credentials["password"] + "\n").encode(), ) descriptor = os.open( staged / "wp-config.php", os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK, ) with os.fdopen(descriptor, "rb") as config: if not stat.S_ISREG(os.fstat(config.fileno()).st_mode): raise ValueError( "WP-CLI did not create its configuration file." ) os.fchmod(config.fileno(), 0o600) if cli.run(staged, "core", "is-installed").returncode: cli.require( staged, "install the WordPress site", "core", "install", f"--url=https://{request.site.domain}", f"--title={request.title}", f"--admin_user={request.username}", f"--admin_email={request.email}", "--skip-email", ) verify_installed_admin(request, cli, staged) version = wordpress_version(cli, staged) staged.chmod(0o750) publish_wordpress(staged, public) return version def verify_installed_admin(request, cli, root): user = cli.require( root, "read the initial administrator", "user", "get", request.username, "--fields=user_email,roles", "--format=json", read=True, ) try: record = json.loads(user.stdout) correct = ( record["user_email"] == request.email and record["roles"] == "administrator" ) except (ValueError, KeyError, TypeError): correct = False if not correct: raise ValueError( "The initial WordPress administrator could not be verified." ) def wordpress_install(request, cli, public, uid, web_gid): if (public / "wp-config.php").is_file(): database = ( cli.require( public, "read the active database", "config", "get", "DB_NAME", "--type=constant", read=True, ) .stdout.decode("ascii", errors="replace") .strip() ) if database != request.database.name: raise ValueError( "This website already contains a WordPress configuration." ) version = wordpress_version(cli, public) if not version: raise ValueError("The live WordPress installation is incomplete.") verify_installed_admin(request, cli, public) return version check_install_target(public) return open_installation(request, cli, public, uid, web_gid) def apply_wordpress_request(request): deadline = monotonic() + 165 if os.geteuid() != 0: raise ValueError("Run WordPress operations on the web node.") try: check_root_file(WP_CLI) except FileNotFoundError: raise ValueError( "Install the verified WP-CLI launcher on the web node." ) from None if ( request.action not in ("inspect", "check-updates") and https_status(request.site)["state"] != "configured" ): raise ValueError("Set up HTTPS for this website first.") mode = fcntl.LOCK_SH if request.action == "inspect" else fcntl.LOCK_EX with web.locked_web_node(mode): if os.path.lexists(website_suspension_path(request.site)): raise ValueError("The website is suspended.") public, uid, web_gid = web.site_storage(request.site) user = web.current_user(request.site.service_user) if user is None or uid == 0 or user.pw_uid != uid: raise ValueError("The website user is unavailable.") runtime = web.SitePaths.for_site(request.site).runtime.version with TemporaryDirectory(prefix="coulobre-wp-cli-") as working: home = Path(working) os.chown(home, uid, user.pw_gid) cli = WordPressCLI(runtime, home, uid, user.pw_gid, deadline) try: return apply_site_operation(request, cli, public, uid, web_gid) except subprocess.TimeoutExpired: raise ValueError("The WordPress command timed out.") from None def apply_site_operation(request, cli, public, uid, web_gid): if request.action in ("inspect", "check-updates", "update"): version = wordpress_version(cli, public) report = {"wp_version": version} if request.action == "check-updates": report["updates"] = [ update.manifest() for update in update_inventory(cli, public, version) ] report["database_name"] = ( database_name(cli, public) if version else "" ) validate_update_inventory(report) elif request.action == "update": apply_update(request, cli, public, version) report["wp_version"] = wordpress_version(cli, public) if request.update["kind"] == "core" and ( report["wp_version"] != request.update["version"] ): raise ValueError( "The updated WordPress version could not be verified." ) return report if request.action == "install": version = wordpress_install(request, cli, public, uid, web_gid) else: version = wordpress_version(cli, public) if not version: raise ValueError( "Install or import WordPress on this website first." ) cli.require( public, "create the administrator. Check the username and email", "user", "create", request.username, request.email, "--role=administrator", "--porcelain", ) try: status = cli.run( public, "eval", SEND_SETUP_LINK, login=request.username, load_plugins=True, ).returncode except (OSError, subprocess.TimeoutExpired): status = 1 return { "wp_version": version, "password_email": "failed" if status else "accepted", }