From 581566b80b231c6515241ce66c8aabf1e4261435 Mon Sep 17 00:00:00 2001 From: Peter van Arkel Date: Sat, 21 Nov 2026 00:16:22 +0100 Subject: [PATCH] Restore DirectAdmin websites into empty web roots --- docs/development.md | 21 +++ src/coulobre/directadmin_website.py | 5 +- src/coulobre/hosting/test_web_node_restore.py | 159 ++++++++++++++++++ src/coulobre/web_node.py | 16 ++ src/coulobre/web_node_apply.py | 16 +- src/coulobre/web_node_restore.py | 74 ++++++++ 6 files changed, 288 insertions(+), 3 deletions(-) create mode 100644 src/coulobre/hosting/test_web_node_restore.py create mode 100644 src/coulobre/web_node_restore.py diff --git a/docs/development.md b/docs/development.md index 5ad8365..1da7d02 100644 --- a/docs/development.md +++ b/docs/development.md @@ -420,6 +420,27 @@ command writes regular files with owner-only permissions and reports the file count, size and number of skipped links or special entries. The staging directory is separate from the live web root. +### Restore a DirectAdmin website on a web node + +Apply the account's web deployment manifest on the web node, then run +the following command with the same manifest and the original backup. + +```sh +sudo /opt/coulobre/bin/coulobre-web-node restore-directadmin coulobre-web-plan-1.json user.admin.customer.tar.zst +``` + +The command restores the manifest's domain into an empty document root. +It reads and validates the entire backup before placing the files. Use +`--source-root private_html` to restore that source directory instead. +The report includes the file count, size and number of skipped entries. + +The hosting account owns the restored files. Apache can read public +files through the `www-data` group. Hidden entries and entries with +private source permissions stay private to the hosting account. The +managed Apache configuration controls the restored site. Any restored +`.htaccess` files are available for review. See the +[Apache AllowOverride reference](https://httpd.apache.org/docs/2.4/mod/core.html#allowoverride). + ## Request an Apache configuration preview Start RabbitMQ and set `COULOBRE_BROKER_URL` to its AMQP URL. The development diff --git a/src/coulobre/directadmin_website.py b/src/coulobre/directadmin_website.py index a239fef..3d9539e 100644 --- a/src/coulobre/directadmin_website.py +++ b/src/coulobre/directadmin_website.py @@ -41,7 +41,7 @@ def stage_website(backup, domain, destination, *, source_root="public_html"): } -def copy_website(backup, domain, source_root, destination): +def copy_website(backup, domain, source_root, destination, *, on_copy=None): account = BackupInventory() matches = {} source_name = None @@ -78,6 +78,9 @@ def copy_website(backup, domain, source_root, destination): total_bytes += member.size else: skipped += 1 + continue + if on_copy is not None: + on_copy(member, target) if account.username is None: raise ValueError("Expected a DirectAdmin account backup with backup/user.conf.") diff --git a/src/coulobre/hosting/test_web_node_restore.py b/src/coulobre/hosting/test_web_node_restore.py new file mode 100644 index 0000000..7eb8991 --- /dev/null +++ b/src/coulobre/hosting/test_web_node_restore.py @@ -0,0 +1,159 @@ +import gzip +import json +import stat +import tarfile +from contextlib import redirect_stdout +from io import BytesIO, StringIO +from pathlib import Path +from tempfile import TemporaryDirectory +from unittest.mock import patch + +from django.test import SimpleTestCase + +from coulobre.web_node import WebSite, main +from coulobre.web_node_restore import copy_website, restore_website + + +class DirectAdminWebRestoreTests(SimpleTestCase): + def setUp(self): + root = Path(self.enterContext(TemporaryDirectory())) + self.site = WebSite(42, "example.net") + self.backup = root / "directadmin.tar.gz" + self.state = root / "state" + self.state.mkdir() + self.marker = self.state / "42.json" + self.marker.write_text(json.dumps(self.site.manifest()), encoding="utf-8") + (self.state / "apply.lock").touch() + self.account = root / "web/42" + self.public = self.account / "public" + self.public.mkdir(parents=True) + self.enterContext(patch("coulobre.web_node_apply.STATE_DIRECTORY", self.state)) + self.enterContext( + patch("coulobre.web_node_apply.WEB_ROOT", self.account.parent) + ) + self.enterContext(patch("coulobre.web_node_restore.os.geteuid", return_value=0)) + self.enterContext(patch("coulobre.web_node_apply.require_root_directory")) + self.enterContext( + patch("coulobre.web_node_apply.read_root_file", side_effect=Path.read_text) + ) + self.installation = self.enterContext( + patch("coulobre.web_node_apply.check_installation", return_value=(1001, 33)) + ) + self.owner = self.enterContext(patch("coulobre.web_node_restore.os.chown")) + + entries = [ + ("backup/user.conf", b"username=client\ndomain=example.net\n", 0o600), + ("domains/example.net/public_html/index.php", b"demo", 0o755), + ("domains/example.net/public_html/.env", b"private", 0o644), + ("domains/example.net/public_html/app.ini", b"private", 0o600), + ("domains/example.net/public_html/assets/site.css", b"assets", 0o644), + ("domains/example.net/public_html/.secret/hidden.txt", b"private", 0o644), + ("domains/example.net/public_html/logs", None, 0o700), + ("domains/example.net/public_html/logs/app.log", b"private", 0o644), + ("domains/other.example/public_html/index.php", b"other", 0o644), + ] + tar = BytesIO() + with tarfile.open(fileobj=tar, mode="w") as archive: + for name, payload, mode in entries: + member = tarfile.TarInfo(name) + member.mode = mode + if payload is None: + member.type = tarfile.DIRTYPE + archive.addfile(member) + else: + member.size = len(payload) + archive.addfile(member, BytesIO(payload)) + self.backup.write_bytes(gzip.compress(tar.getvalue())) + + def restore(self): + return restore_website(self.site, self.backup, "public_html") + + def test_restore_cli_publishes_files_with_hosting_permissions(self): + manifest = self.state.parent / "site.json" + manifest.write_text(json.dumps(self.site.manifest()), encoding="utf-8") + output = self.enterContext(redirect_stdout(StringIO())) + + self.assertEqual( + main(["restore-directadmin", str(manifest), str(self.backup)]), + 0, + ) + + report = json.loads(output.getvalue()) + self.assertEqual(report["kind"], "directadmin_website_restore") + self.assertEqual(report["files"], 6) + self.assertEqual(report["document_root"], str(self.public)) + self.assertEqual(report["domain"], self.site.domain) + self.assertEqual((self.public / "index.php").read_bytes(), b"demo") + self.assertEqual(list(self.account.iterdir()), [self.public]) + modes = { + ".": 0o750, + "index.php": 0o640, + ".env": 0o600, + "app.ini": 0o600, + "assets": 0o750, + "assets/site.css": 0o640, + ".secret": 0o700, + "logs": 0o700, + } + for entry, mode in modes.items(): + with self.subTest(entry=entry): + self.assertEqual( + stat.S_IMODE((self.public / entry).stat().st_mode), mode + ) + self.assertEqual(self.owner.call_count, 10) + for call in self.owner.call_args_list: + self.assertEqual(call.args[1:], (1001, 33)) + + def test_non_empty_document_root_refuses_restore(self): + existing = self.public / "index.php" + existing.write_bytes(b"existing") + + with self.assertRaisesRegex(ValueError, "empty document root"): + self.restore() + + self.assertEqual(list(self.public.iterdir()), [existing]) + self.assertEqual(existing.read_bytes(), b"existing") + + def test_atomic_publish_preserves_a_file_created_during_restore(self): + existing = self.public / "new.txt" + + def write_to_live_root(*args, **kwargs): + summary = copy_website(*args, **kwargs) + existing.write_bytes(b"new data") + return summary + + with ( + patch( + "coulobre.web_node_restore.copy_website", side_effect=write_to_live_root + ), + self.assertRaisesRegex(ValueError, "empty document root"), + ): + self.restore() + + self.assertEqual(list(self.public.iterdir()), [existing]) + self.assertEqual(existing.read_bytes(), b"new data") + self.assertEqual(list(self.account.iterdir()), [self.public]) + + def test_incomplete_backup_leaves_live_document_root_untouched(self): + inode = self.public.stat().st_ino + self.backup.write_bytes(self.backup.read_bytes()[:-4]) + + with self.assertRaisesRegex( + ValueError, "not a readable or complete tar archive" + ): + self.restore() + + self.assertEqual(self.public.stat().st_ino, inode) + self.assertEqual(list(self.public.iterdir()), []) + self.assertEqual(list(self.account.iterdir()), [self.public]) + + def test_restore_checks_manifest_against_registered_site_first(self): + self.marker.write_text( + json.dumps(WebSite(42, "different.example").manifest()), encoding="utf-8" + ) + + with self.assertRaisesRegex(ValueError, "different manifest"): + self.restore() + + self.installation.assert_not_called() + self.assertEqual(list(self.public.iterdir()), []) diff --git a/src/coulobre/web_node.py b/src/coulobre/web_node.py index 40a9146..4b5d668 100644 --- a/src/coulobre/web_node.py +++ b/src/coulobre/web_node.py @@ -6,6 +6,7 @@ from importlib.resources import files from pathlib import Path from string import Template +from .directadmin import DOCUMENT_ROOTS from .domain_names import canonical_domain MANIFEST_VERSION = 1 @@ -79,6 +80,13 @@ def main(argv=None): "status", help="Check a site's local configuration and services." ) status.add_argument("manifest", type=Path) + restore = commands.add_parser( + "restore-directadmin", + help="Restore a DirectAdmin website into an empty web root.", + ) + restore.add_argument("manifest", type=Path) + restore.add_argument("backup", type=Path) + restore.add_argument("--source-root", choices=DOCUMENT_ROOTS, default="public_html") args = parser.parse_args(argv) try: @@ -95,6 +103,14 @@ def main(argv=None): report = site_status(site) print(json.dumps(report, indent=2)) return 0 if report["state"] == "configured" else 2 + elif args.command == "restore-directadmin": + from .web_node_restore import restore_website + + print( + json.dumps( + restore_website(site, args.backup, args.source_root), indent=2 + ) + ) else: sys.stdout.write(site.render(args.configuration)) except (OSError, ValueError) as error: diff --git a/src/coulobre/web_node_apply.py b/src/coulobre/web_node_apply.py index f861ba3..42836f9 100644 --- a/src/coulobre/web_node_apply.py +++ b/src/coulobre/web_node_apply.py @@ -85,14 +85,25 @@ def site_status(site): with (STATE_DIRECTORY / "apply.lock").open("r") as lock: fcntl.flock(lock, fcntl.LOCK_SH) try: - if json.loads(read_root_file(marker)) != site.manifest(): - raise ValueError("The account is reserved with a different manifest.") + check_reservation(site) check_installation(site, SitePaths.for_site(site)) except (OSError, ValueError) as error: return {**report, "state": "needs_attention", "problem": str(error)} return {**report, "state": "configured"} +def check_reservation(site): + marker = STATE_DIRECTORY / f"{site.account_id}.json" + try: + saved = json.loads(read_root_file(marker)) + except FileNotFoundError: + raise ValueError( + "Apply the site manifest before restoring website files." + ) from None + if saved != site.manifest(): + raise ValueError("The account is reserved with a different manifest.") + + def check_installation(site, paths): for directory in ( paths.account, @@ -111,6 +122,7 @@ def check_installation(site, paths): check_services() if not socket_exists(paths.socket): raise ValueError(f"PHP-FPM is missing the site socket at {paths.socket}.") + return uid, gid def check_services(): diff --git a/src/coulobre/web_node_restore.py b/src/coulobre/web_node_restore.py new file mode 100644 index 0000000..4256f4f --- /dev/null +++ b/src/coulobre/web_node_restore.py @@ -0,0 +1,74 @@ +import errno +import fcntl +import os +from pathlib import Path +from tempfile import TemporaryDirectory + +from . import web_node_apply +from .directadmin_website import copy_website + + +def restore_website(site, backup, source_root): + if os.geteuid() != 0: + raise ValueError("Run restore-directadmin as root on the web node.") + + web_node_apply.require_root_directory(web_node_apply.STATE_DIRECTORY) + with (web_node_apply.STATE_DIRECTORY / "apply.lock").open("r") as lock: + fcntl.flock(lock, fcntl.LOCK_EX) + web_node_apply.check_reservation(site) + paths = web_node_apply.SitePaths.for_site(site) + uid, gid = web_node_apply.check_installation(site, paths) + public = paths.account / "public" + if any(public.iterdir()): + raise ValueError("Restore requires an empty document root.") + + with TemporaryDirectory( + dir=paths.account, prefix=".directadmin-restore-" + ) as directory: + staged = Path(directory) / "public" + staged.mkdir(mode=0o700) + private = set() + + def remember_private_entry(member, target): + access = 0o011 if member.isdir() else 0o044 + if not member.mode & access: + private.add(target) + + summary = copy_website( + backup, site.domain, source_root, staged, on_copy=remember_private_entry + ) + prepare_web_permissions(staged, uid, gid, private) + try: + # A directory rename can replace the live root only while it is empty. + os.replace(staged, public) + except OSError as error: + if error.errno not in (errno.ENOTEMPTY, errno.EEXIST): + raise + raise ValueError("Restore requires an empty document root.") from None + + return { + **site.manifest(), + "kind": "directadmin_website_restore", + "source_root": source_root, + "document_root": str(public), + **summary, + } + + +def prepare_web_permissions(root, uid, gid, private): + root_is_private = root in private + for directory, _, filenames in root.walk(top_down=False, on_error=raise_walk_error): + for filename in filenames: + path = directory / filename + restricted = root_is_private or path in private or filename.startswith(".") + path.chmod(0o600 if restricted else 0o640) + os.chown(path, uid, gid, follow_symlinks=False) + restricted = directory != root and ( + root_is_private or directory in private or directory.name.startswith(".") + ) + directory.chmod(0o700 if restricted else 0o750) + os.chown(directory, uid, gid, follow_symlinks=False) + + +def raise_walk_error(error): + raise error