diff --git a/docs/deployment.md b/docs/deployment.md index 109c781..b9fa8a0 100644 --- a/docs/deployment.md +++ b/docs/deployment.md @@ -312,6 +312,13 @@ SFTP sessions before transferring the hosting account to another customer. Connect to the web node's SSH hostname and port, which may differ from the hostname that a reverse proxy uses for web traffic. +## Back up hosted website files + +Use the web node commands to archive a website's document root and +restore the entire tree or a selected file. The archive stays on the +web node at the path supplied by the operator. +[Website backup and restore](development.md#back-up-and-restore-hosted-website-files) + ## Provision local databases from the panel Enable the [database provisioning socket](development.md#enable-local-database-provisioning) diff --git a/docs/development.md b/docs/development.md index 38fff1c..b4134e3 100644 --- a/docs/development.md +++ b/docs/development.md @@ -777,6 +777,48 @@ sudo /opt/coulobre/bin/coulobre-web-node set-sftp-keys \ sftp coulobre-1@web-node.example.org ``` +## Back up and restore hosted website files + +Apply the site's deployment manifest on the web node. Use that manifest +to create a native website backup in a root-controlled directory. + +```sh +sudo install -d -m 0700 /var/backups/coulobre +sudo /opt/coulobre/bin/coulobre-web-node backup-site \ + coulobre-web-plan-1.json /var/backups/coulobre/site.tar.gz +``` + +The root-only archive contains the account and domain identity plus +directories and regular files from the document root. The backup report +counts symbolic links and other non-regular entries as skipped. +Use a new archive filename for each backup. Pause SFTP uploads and +application writes for a consistent copy. The backup detects changes +while reading entries and requires site-owned files with Unix mode +permissions on the document root's filesystem. + +To recover one file, select its path relative to the document root. +Its parent directory must already exist. To overwrite an existing +site-owned file at that path, add `--replace`. + +```sh +sudo /opt/coulobre/bin/coulobre-web-node restore-site \ + coulobre-web-plan-1.json /var/backups/coulobre/site.tar.gz \ + --file assets/site.css --replace +``` + +To restore the entire archive, run the command with an empty document +root for the same account and domain. + +```sh +sudo /opt/coulobre/bin/coulobre-web-node restore-site \ + coulobre-web-plan-1.json /var/backups/coulobre/site.tar.gz +``` + +Use a root-owned archive with mode `0600`. The node validates the +entire archive before publishing restored files. Restored files belong +to the site account, with the Apache read access recorded in the +backup. The website can be recovered while its web services are stopped. + ## Run an isolated PHP test site Open a completed preview for the account's current domain and select **Download diff --git a/src/coulobre/hosting/test_web_node_backup.py b/src/coulobre/hosting/test_web_node_backup.py new file mode 100644 index 0000000..9ce0699 --- /dev/null +++ b/src/coulobre/hosting/test_web_node_backup.py @@ -0,0 +1,223 @@ +import json +import os +import stat +import tarfile +from contextlib import nullcontext, 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_backup import ( + backup_website, + restore_native_website, + write_metadata, +) + + +class NativeWebsiteBackupTests(SimpleTestCase): + def setUp(self): + self.root = Path(self.enterContext(TemporaryDirectory())) + self.public = self.root / "public" + self.public.mkdir(mode=0o750) + self.archive = self.root / "site.tar.gz" + self.site = WebSite(42, "example.net") + uid, gid = os.geteuid(), os.getegid() + self.enterContext( + patch("coulobre.web_node_backup.os.geteuid", return_value=0) + ) + self.enterContext( + patch("coulobre.web_node_backup.require_root_directory") + ) + self.enterContext(patch("coulobre.web_node_backup.check_root_file")) + self.enterContext( + patch( + "coulobre.web_node_backup.locked_web_node", + side_effect=lambda mode: nullcontext(), + ) + ) + self.enterContext( + patch( + "coulobre.web_node_backup.site_storage", + return_value=(self.public, uid, gid), + ) + ) + + def file(self, name, content, mode=0o640): + path = self.public / name + path.write_bytes(content) + path.chmod(mode) + return path + + def test_cli_round_trip_keeps_private_files_private_and_skips_links(self): + index = self.file("index.php", b"original") + private = self.public / "private" + private.mkdir(mode=0o700) + secret = self.file("private/secret.txt", b"secret") + link = self.public / "link" + link.symlink_to(self.root) + manifest = self.root / "site.json" + manifest.write_text(json.dumps(self.site.manifest()), encoding="utf-8") + output = StringIO() + + with redirect_stdout(output): + self.assertEqual( + main(["backup-site", str(manifest), str(self.archive)]), 0 + ) + report = json.loads(output.getvalue()) + self.assertEqual(report["files"], 2) + self.assertEqual(report["skipped_non_regular_entries"], 1) + self.assertEqual(stat.S_IMODE(self.archive.stat().st_mode), 0o600) + + index.unlink() + secret.unlink() + private.rmdir() + link.unlink() + with redirect_stdout(StringIO()): + self.assertEqual( + main(["restore-site", str(manifest), str(self.archive)]), 0 + ) + self.assertEqual(index.read_bytes(), b"original") + self.assertEqual(stat.S_IMODE(index.stat().st_mode), 0o640) + self.assertEqual(secret.read_bytes(), b"secret") + self.assertEqual(stat.S_IMODE(secret.stat().st_mode), 0o600) + self.assertFalse(link.is_symlink()) + + def test_single_file_restore_replaces_only_the_selected_file(self): + assets = self.public / "assets" + assets.mkdir() + selected = self.file("assets/site.css", b"original") + other = self.file("index.php", b"original neighbor") + backup_website(self.site, self.archive) + selected.write_bytes(b"changed") + other.write_bytes(b"live neighbor") + with self.assertRaisesMessage(ValueError, "Use --replace"): + restore_native_website( + self.site, self.archive, filename="assets/site.css" + ) + + report = restore_native_website( + self.site, self.archive, filename="assets/site.css", replace=True + ) + self.assertEqual(report["files"], 1) + self.assertEqual(selected.read_bytes(), b"original") + self.assertEqual(other.read_bytes(), b"live neighbor") + + def test_single_file_restore_recovers_a_deleted_file(self): + assets = self.public / "assets" + assets.mkdir() + selected = self.file("assets/site.css", b"original") + backup_website(self.site, self.archive) + selected.unlink() + + restore_native_website( + self.site, self.archive, filename="assets/site.css" + ) + + self.assertEqual(selected.read_bytes(), b"original") + + def test_file_changed_during_backup_leaves_no_partial_archive(self): + live = self.file("index.php", b"old") + + def change_file(target, name): + if name == "public/index.php": + live.write_bytes(b"newer content") + + with ( + patch( + "coulobre.web_node_backup.check_mode_permissions", + side_effect=change_file, + ), + self.assertRaisesMessage( + ValueError, "Website content changed during backup" + ), + ): + backup_website(self.site, self.archive) + + self.assertFalse(self.archive.exists()) + + def test_existing_archive_and_nonempty_webroot_are_preserved(self): + live = self.file("index.php", b"live") + self.archive.write_bytes(b"existing") + with self.assertRaisesMessage( + ValueError, "new website backup filename" + ): + backup_website(self.site, self.archive) + self.assertEqual(self.archive.read_bytes(), b"existing") + with self.assertRaisesMessage(ValueError, "empty document root"): + restore_native_website(self.site, self.archive) + self.assertEqual(live.read_bytes(), b"live") + + def test_damaged_archive_does_not_replace_a_selected_file(self): + live = self.file("index.php", b"old") + backup_website(self.site, self.archive) + self.archive.write_bytes(self.archive.read_bytes()[:-4]) + live.write_bytes(b"current") + with self.assertRaisesMessage( + ValueError, "not a readable or complete" + ): + restore_native_website( + self.site, self.archive, filename="index.php", replace=True + ) + self.assertEqual(live.read_bytes(), b"current") + + def test_restoring_to_an_unmatched_site_does_not_publish_files(self): + live = self.file("index.php", b"old") + backup_website(self.site, self.archive) + live.unlink() + with self.assertRaisesMessage( + ValueError, "different account or domain" + ): + restore_native_website(WebSite(43, self.site.domain), self.archive) + self.assertEqual(list(self.public.iterdir()), []) + + def test_single_file_restore_refuses_a_symlink_parent(self): + assets = self.public / "assets" + assets.mkdir() + self.file("assets/site.css", b"backup content") + backup_website(self.site, self.archive) + outside = self.root / "outside" + assets.rename(outside) + outside_file = outside / "site.css" + outside_file.write_bytes(b"outside content") + assets.symlink_to(outside) + + with self.assertRaises(OSError): + restore_native_website( + self.site, + self.archive, + filename="assets/site.css", + replace=True, + ) + self.assertEqual(outside_file.read_bytes(), b"outside content") + + def test_unsupported_archive_entries_leave_the_webroot_empty(self): + with tarfile.open(self.archive, mode="w:gz") as archive: + write_metadata(archive, self.site) + root = tarfile.TarInfo("public") + root.type = tarfile.DIRTYPE + archive.addfile(root) + link = tarfile.TarInfo("public/external") + link.type = tarfile.SYMTYPE + link.linkname = "/etc/passwd" + archive.addfile(link, BytesIO()) + + with self.assertRaisesMessage(ValueError, "unsupported entry"): + restore_native_website(self.site, self.archive) + self.assertEqual(list(self.public.iterdir()), []) + + def test_backup_rejects_acl_instead_of_widening_access(self): + with ( + patch( + "coulobre.web_node_backup.os.listxattr", + return_value=["system.posix_acl_access"], + ), + self.assertRaisesMessage( + ValueError, "require Unix mode permissions" + ), + ): + backup_website(self.site, self.archive) + self.assertFalse(self.archive.exists()) diff --git a/src/coulobre/web_node.py b/src/coulobre/web_node.py index 0c2a9ba..78de9a0 100644 --- a/src/coulobre/web_node.py +++ b/src/coulobre/web_node.py @@ -127,7 +127,21 @@ def main(argv=None): restore.add_argument( "--source-root", choices=DOCUMENT_ROOTS, default="public_html" ) + backup_site = commands.add_parser( + "backup-site", help="Back up a hosted site's document root." + ) + backup_site.add_argument("manifest", type=Path) + backup_site.add_argument("archive", type=Path) + restore_site = commands.add_parser( + "restore-site", help="Restore a native website backup." + ) + restore_site.add_argument("manifest", type=Path) + restore_site.add_argument("archive", type=Path) + restore_site.add_argument("--file", help="Restore one document-root path.") + restore_site.add_argument("--replace", action="store_true") args = parser.parse_args(argv) + if args.command == "restore-site" and args.replace and args.file is None: + parser.error("--replace requires --file.") if args.command == "apply-request": from .web_node_apply import apply_site @@ -194,6 +208,17 @@ def main(argv=None): indent=2, ) ) + elif args.command == "backup-site": + from .web_node_backup import backup_website + + print(json.dumps(backup_website(site, args.archive), indent=2)) + elif args.command == "restore-site": + from .web_node_backup import restore_native_website + + report = restore_native_website( + site, args.archive, filename=args.file, replace=args.replace + ) + print(json.dumps(report, indent=2)) else: sys.stdout.write(site.render(args.configuration)) except (OSError, ValueError) as error: diff --git a/src/coulobre/web_node_backup.py b/src/coulobre/web_node_backup.py new file mode 100644 index 0000000..c365e33 --- /dev/null +++ b/src/coulobre/web_node_backup.py @@ -0,0 +1,332 @@ +import fcntl +import json +import os +import stat +import tarfile +from contextlib import contextmanager +from io import BytesIO +from pathlib import Path +from tempfile import NamedTemporaryFile, TemporaryDirectory + +from .directadmin import backup_members, member_path, open_backup +from .directadmin_website import copy_member +from .node_files import check_root_file, require_root_directory +from .web_node_apply import ( + SitePaths, + check_public_directory, + check_reservation, + check_system_account, + locked_web_node, +) +from .web_node_restore import publish_empty_webroot + +BACKUP_VERSION = 1 +BACKUP_KIND = "coulobre_website_backup" +METADATA_NAME = "manifest.json" + + +def backup_website(site, destination): + if os.geteuid() != 0: + raise ValueError("Run backup-site as root on the web node.") + destination = destination.absolute() + require_root_directory(destination.parent) + if os.path.lexists(destination): + raise ValueError("Choose a new website backup filename.") + + with locked_web_node(fcntl.LOCK_SH): + public, uid, gid = site_storage(site) + with NamedTemporaryFile(dir=destination.parent) as staged: + with tarfile.open( + fileobj=staged, mode="w:gz", format=tarfile.PAX_FORMAT + ) as archive: + write_metadata(archive, site) + summary = archive_webroot(archive, public, uid, gid) + staged.flush() + os.fsync(staged.fileno()) + os.link(staged.name, destination) + return site.manifest() | { + "kind": BACKUP_KIND, + "archive": str(destination), + **summary, + } + + +def restore_native_website(site, backup, *, filename=None, replace=False): + if os.geteuid() != 0: + raise ValueError("Run restore-site as root on the web node.") + if replace and filename is None: + raise ValueError("Choose a file when replacing live content.") + selected = relative_file_parts(filename) if filename is not None else None + backup = backup.absolute() + require_root_directory(backup.parent) + check_root_file(backup, mode=0o600) + with locked_web_node(fcntl.LOCK_EX): + public, uid, gid = site_storage(site) + if selected is None and any(public.iterdir()): + raise ValueError("Restore requires an empty document root.") + with TemporaryDirectory( + dir=public.parent, prefix=".coulobre-restore-" + ) as directory: + check_mode_permissions(directory, directory) + staged = Path(directory) / "public" + summary = extract_site_archive( + site, backup, staged, selected, uid, gid + ) + if selected is None: + publish_empty_webroot(staged, public) + else: + publish_restored_file(staged, public, selected, uid, replace) + return site.manifest() | { + "kind": "coulobre_website_restore", + "document_root": str(public), + "file": filename, + **summary, + } + + +def site_storage(site): + check_reservation(site) + paths = SitePaths.for_site(site) + require_root_directory(paths.account) + user = site.configuration()["service_user"] + uid, gid = check_system_account(user, paths.account) + public = paths.account / "public" + check_public_directory(public, uid, gid) + return public, uid, gid + + +def write_metadata(archive, site): + metadata = { + "version": BACKUP_VERSION, + "kind": BACKUP_KIND, + "site": site.manifest(), + } + body = json.dumps(metadata).encode("ascii") + member = tarfile.TarInfo(METADATA_NAME) + member.mode = 0o600 + member.size = len(body) + archive.addfile(member, BytesIO(body)) + + +@contextmanager +def open_directory(name, *, parent=None): + fd = os.open( + name, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW, dir_fd=parent + ) + try: + yield fd + finally: + os.close(fd) + + +def archive_webroot(archive, public, uid, gid): + summary = {"files": 0, "bytes": 0, "skipped_non_regular_entries": 0} + with open_directory(public) as fd: + root = os.fstat(fd) + if root.st_uid != uid or root.st_gid != gid: + raise ValueError( + "The website document root changed during backup." + ) + archive_directory(archive, fd, "public", root, uid, gid, True, summary) + return summary + + +def archive_directory( + archive, fd, name, initial, uid, gid, accessible, summary +): + check_mode_permissions(fd, name) + mode = archived_mode(initial, gid, accessible) + archive.addfile(archive_entry(name, initial, mode)) + for entry in sorted(os.listdir(fd)): + path = f"{name}/{entry}" + info = os.stat(entry, dir_fd=fd, follow_symlinks=False) + if not (stat.S_ISDIR(info.st_mode) or stat.S_ISREG(info.st_mode)): + summary["skipped_non_regular_entries"] += 1 + continue + if info.st_uid != uid or info.st_dev != initial.st_dev: + raise ValueError(f"Unexpected owner or filesystem for {path}.") + visible = bool(mode & 0o010) + if stat.S_ISDIR(info.st_mode): + with open_directory(entry, parent=fd) as child: + check_snapshot(os.fstat(child), info, path) + archive_directory( + archive, child, path, info, uid, gid, visible, summary + ) + else: + open_flags = os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK + with os.fdopen( + os.open(entry, open_flags, dir_fd=fd), "rb" + ) as source: + check_snapshot(os.fstat(source.fileno()), info, path) + check_mode_permissions(source.fileno(), path) + member = archive_entry( + path, info, archived_mode(info, gid, visible) + ) + archive.addfile(member, source) + check_snapshot(os.fstat(source.fileno()), info, path) + summary["files"] += 1 + summary["bytes"] += info.st_size + check_snapshot(os.fstat(fd), initial, name) + + +def archived_mode(info, gid, accessible): + group_access = info.st_mode >> (3 if info.st_gid == gid else 0) + if not accessible: + group_access = 0 + if stat.S_ISDIR(info.st_mode): + return 0o700 | ((group_access & 0o5) << 3) + return 0o600 | ((group_access & 0o4) << 3) + + +def check_mode_permissions(target, name): + if {"system.posix_acl_access", "system.posix_acl_default"}.intersection( + os.listxattr(target) + ): + raise ValueError( + f"Website backups require Unix mode permissions at {name}." + ) + + +def archive_entry(name, info, mode): + member = tarfile.TarInfo(name) + member.mode = mode + member.mtime = info.st_mtime_ns // 1_000_000_000 + if stat.S_ISDIR(info.st_mode): + member.type = tarfile.DIRTYPE + else: + member.size = info.st_size + return member + + +def check_snapshot(current, original, path): + if ( + current.st_dev != original.st_dev + or current.st_ino != original.st_ino + or current.st_mode != original.st_mode + or current.st_uid != original.st_uid + or current.st_gid != original.st_gid + or current.st_size != original.st_size + or current.st_mtime_ns != original.st_mtime_ns + or current.st_ctime_ns != original.st_ctime_ns + ): + raise ValueError(f"Website content changed during backup at {path}.") + + +def extract_site_archive(site, backup, staged, selected, uid, gid): + summary = {"files": 0, "bytes": 0} + directories = set() + entries = set() + with open_backup(backup) as archive: + members = backup_members(archive) + validate_metadata(archive, next(members, None), site) + for member in members: + parts = member_path(member) + if not parts or parts[0] != "public": + raise ValueError("The backup contains an unexpected path.") + path = parts[1:] + if path in entries: + raise ValueError("The backup contains a duplicate path.") + entries.add(path) + if path and path[:-1] not in directories: + raise ValueError("The backup is missing a parent directory.") + if member.isdir(): + directories.add(path) + if selected is None: + target = staged.joinpath(*path) + target.mkdir(mode=0o700) + mode = (0o700 | (member.mode & 0o050)) if path else 0o750 + set_web_permissions(target, uid, gid, mode) + elif member.isreg() and path: + if selected is None or path == selected: + target = ( + staged.joinpath(*path) if selected is None else staged + ) + copy_member(archive, member, target) + set_web_permissions( + target, uid, gid, 0o600 | (member.mode & 0o040) + ) + os.utime(target, (member.mtime, member.mtime)) + summary["files"] += 1 + summary["bytes"] += member.size + else: + raise ValueError("The backup contains an unsupported entry.") + if () not in directories: + raise ValueError("The backup is missing its website document root.") + if selected is not None and not summary["files"]: + raise ValueError("The selected file is not in the website backup.") + return summary + + +def validate_metadata(archive, member, site): + if ( + member is None + or member.name != METADATA_NAME + or not member.isreg() + or not 0 < member.size <= 4096 + ): + raise ValueError("Expected a native website backup manifest.") + with archive.extractfile(member) as source: + metadata = json.load(source) + if ( + not isinstance(metadata, dict) + or metadata.keys() != {"version", "kind", "site"} + or type(metadata["version"]) is not int + or metadata["version"] != BACKUP_VERSION + or metadata["kind"] != BACKUP_KIND + ): + raise ValueError("Expected a supported native website backup.") + if type(site).from_manifest(metadata["site"]) != site: + raise ValueError( + "The website backup is for a different account or domain." + ) + + +def set_web_permissions(path, uid, gid, mode): + os.chown(path, uid, gid, follow_symlinks=False) + path.chmod(mode) + + +def relative_file_parts(filename): + parts = tuple(filename.split("/")) + if any(part in ("", ".", "..") for part in parts): + raise ValueError("Choose a file path relative to the document root.") + return parts + + +def publish_restored_file(staged, public, selected, uid, replace): + with ( + open_directory(public) as fd, + open_restore_parent(fd, selected[:-1], uid) as parent, + ): + name = selected[-1] + if not replace: + try: + os.link(staged, name, dst_dir_fd=parent) + except FileExistsError: + raise ValueError( + "The selected file already exists. " + "Use --replace to overwrite it." + ) from None + return + try: + info = os.stat(name, dir_fd=parent, follow_symlinks=False) + except FileNotFoundError: + pass + else: + if not stat.S_ISREG(info.st_mode) or info.st_uid != uid: + raise ValueError("Replace requires a regular site-owned file.") + os.replace(staged, name, dst_dir_fd=parent) + + +@contextmanager +def open_restore_parent(fd, parts, uid): + if not parts: + yield fd + return + with open_directory(parts[0], parent=fd) as child: + if os.fstat(child).st_uid != uid: + raise ValueError( + "The restore path contains a directory owned by another user." + ) + with open_restore_parent(child, parts[1:], uid) as parent: + yield parent diff --git a/src/coulobre/web_node_restore.py b/src/coulobre/web_node_restore.py index f54db09..f85c496 100644 --- a/src/coulobre/web_node_restore.py +++ b/src/coulobre/web_node_restore.py @@ -42,15 +42,7 @@ def restore_website(site, backup, source_root): on_copy=remember_private_entry, ) prepare_web_permissions(staged, uid, gid, private) - try: - # A rename can replace the live root 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 + publish_empty_webroot(staged, public) return { **site.manifest(), @@ -61,6 +53,16 @@ def restore_website(site, backup, source_root): } +def publish_empty_webroot(staged, public): + try: + # A rename can replace the live root 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 + + def prepare_web_permissions(root, uid, gid, private): root_is_private = root in private for directory, _, filenames in root.walk(