Restore website files from local account backup bundles
This commit is contained in:
1 parent
1f57e63f20
commit
b9e54c9575
6 files changed
+232
-29
No files matched your search
@@ -4,6 +4,7 @@ import json
|
||||
import os
|
||||
import tarfile
|
||||
import zlib
|
||||
from contextlib import contextmanager
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
from shutil import copyfileobj
|
||||
@@ -121,8 +122,17 @@ def main(argv=None):
|
||||
commands.add_parser(
|
||||
"create-request", help="Create a local backup for the panel worker."
|
||||
)
|
||||
commands.add_parser(
|
||||
"restore-website-request",
|
||||
help="Restore website files for the panel worker.",
|
||||
)
|
||||
args = parser.parse_args(argv)
|
||||
|
||||
if args.command == "restore-website-request":
|
||||
from .account_restore_request import serve_website_restore
|
||||
|
||||
return serve_website_restore()
|
||||
|
||||
if args.command == "create-request":
|
||||
from .account_backup_request import serve_backup_request
|
||||
|
||||
@@ -201,15 +211,11 @@ def pack_backup(backup, directory, archive):
|
||||
os.link(staged.name, archive)
|
||||
|
||||
|
||||
def unpack_backup(archive, directory):
|
||||
@contextmanager
|
||||
def open_account_bundle(archive):
|
||||
archive = private_path(archive)
|
||||
check_root_file(archive, mode=0o600)
|
||||
directory = private_path(directory, new=True)
|
||||
with (
|
||||
ZipFile(archive) as bundle,
|
||||
TemporaryDirectory(dir=directory.parent) as temporary,
|
||||
):
|
||||
staged = Path(temporary)
|
||||
with ZipFile(archive) as bundle:
|
||||
entries = bundle.infolist()
|
||||
if any(
|
||||
entry.compress_type != ZIP_STORED or entry.flag_bits & 1
|
||||
@@ -226,6 +232,16 @@ def unpack_backup(archive, directory):
|
||||
with bundle.open(manifests[0]) as source:
|
||||
backup = read_backup_manifest(source)
|
||||
validate_bundle_entries(entries, backup)
|
||||
yield bundle, backup
|
||||
|
||||
|
||||
def unpack_backup(archive, directory):
|
||||
directory = private_path(directory, new=True)
|
||||
with (
|
||||
open_account_bundle(archive) as (bundle, backup),
|
||||
TemporaryDirectory(dir=directory.parent) as temporary,
|
||||
):
|
||||
staged = Path(temporary)
|
||||
write_new_file(
|
||||
staged / MANIFEST_NAME, manifest_text(backup), mode=0o600
|
||||
)
|
||||
|
||||
@@ -12,7 +12,7 @@ from .account_backup import (
|
||||
read_backup_manifest,
|
||||
)
|
||||
from .database_node import DEFAULT_SOCKET
|
||||
from .node_files import check_root_file, require_root_directory
|
||||
from .node_files import check_root_file, locked_root_directory
|
||||
from .node_requests import serve_apply_request
|
||||
|
||||
REQUEST_VERSION = 1
|
||||
@@ -71,8 +71,6 @@ def serve_backup_request():
|
||||
|
||||
|
||||
def create_requested_backup(request):
|
||||
import fcntl
|
||||
|
||||
if os.geteuid() != 0:
|
||||
raise ValueError("Run create-request as root on the backup node.")
|
||||
if (
|
||||
@@ -80,15 +78,8 @@ def create_requested_backup(request):
|
||||
and os.environ.get("COULOBRE_LOCAL_ACCOUNT_BACKUP_MAIL") != "1"
|
||||
):
|
||||
raise ValueError("Enable mailbox backups on the local backup node.")
|
||||
require_root_directory(BACKUP_DIRECTORY)
|
||||
directory = os.open(
|
||||
BACKUP_DIRECTORY, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW
|
||||
)
|
||||
try:
|
||||
fcntl.flock(directory, fcntl.LOCK_EX)
|
||||
with locked_root_directory(BACKUP_DIRECTORY):
|
||||
ensure_requested_archive(request)
|
||||
finally:
|
||||
os.close(directory)
|
||||
|
||||
|
||||
def ensure_requested_archive(request):
|
||||
|
||||
@@ -0,0 +1,184 @@
|
||||
import errno
|
||||
import json
|
||||
import os
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
from shutil import copyfileobj
|
||||
from tempfile import TemporaryDirectory
|
||||
from uuid import UUID
|
||||
from zipfile import BadZipFile
|
||||
|
||||
from .account_backup import CHUNK_BYTES, open_account_bundle
|
||||
from .account_backup_request import BACKUP_TIMEOUT_SECONDS, backup_archive
|
||||
from .node_files import locked_root_directory, read_root_file, write_new_file
|
||||
from .node_requests import serve_apply_request
|
||||
from .web_node import WebSite
|
||||
|
||||
REQUEST_VERSION = 1
|
||||
RESTORE_DIRECTORY = Path("/var/lib/coulobre/account-restores")
|
||||
RESTORE_SOCKET = "/run/coulobre-account-restore.sock"
|
||||
RESTORE_TIMEOUT_SECONDS = BACKUP_TIMEOUT_SECONDS
|
||||
MAX_RESTORE_PATH_BYTES = 1024
|
||||
|
||||
|
||||
def validate_restore_path(filename):
|
||||
from .web_node_backup import relative_file_parts
|
||||
|
||||
if not isinstance(filename, str) or not filename.isprintable():
|
||||
raise ValueError("Choose a file path relative to the document root.")
|
||||
parts = relative_file_parts(filename)
|
||||
if len(filename.encode("utf-8")) > MAX_RESTORE_PATH_BYTES or any(
|
||||
len(part.encode("utf-8")) > 255 for part in parts
|
||||
):
|
||||
raise ValueError("The restore path is too long.")
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class WebsiteRestoreRequest:
|
||||
restore_id: UUID
|
||||
backup_id: UUID
|
||||
site: WebSite
|
||||
filename: str | None
|
||||
replace: bool
|
||||
|
||||
def __post_init__(self):
|
||||
if type(self.replace) is not bool:
|
||||
raise ValueError("Expected a boolean replacement option.")
|
||||
if self.filename is not None:
|
||||
validate_restore_path(self.filename)
|
||||
elif self.replace:
|
||||
raise ValueError("Choose a file when replacing live content.")
|
||||
|
||||
@classmethod
|
||||
def from_manifest(cls, data):
|
||||
if (
|
||||
not isinstance(data, dict)
|
||||
or data.keys()
|
||||
!= {
|
||||
"version",
|
||||
"restore_id",
|
||||
"backup_id",
|
||||
"site",
|
||||
"filename",
|
||||
"replace",
|
||||
}
|
||||
or type(data["version"]) is not int
|
||||
or data["version"] != REQUEST_VERSION
|
||||
):
|
||||
raise ValueError("Expected a local website restore request.")
|
||||
return cls(
|
||||
parse_uuid(data["restore_id"]),
|
||||
parse_uuid(data["backup_id"]),
|
||||
WebSite.from_manifest(data["site"]),
|
||||
data["filename"],
|
||||
data["replace"],
|
||||
)
|
||||
|
||||
def manifest(self):
|
||||
return {
|
||||
"version": REQUEST_VERSION,
|
||||
"restore_id": str(self.restore_id),
|
||||
"backup_id": str(self.backup_id),
|
||||
"site": self.site.manifest(),
|
||||
"filename": self.filename,
|
||||
"replace": self.replace,
|
||||
}
|
||||
|
||||
|
||||
def parse_uuid(value):
|
||||
if isinstance(value, str):
|
||||
try:
|
||||
identifier = UUID(value)
|
||||
except ValueError:
|
||||
pass
|
||||
else:
|
||||
if str(identifier) == value:
|
||||
return identifier
|
||||
raise ValueError("Expected a canonical restore or backup ID.")
|
||||
|
||||
|
||||
def serve_website_restore():
|
||||
return serve_apply_request(
|
||||
REQUEST_VERSION,
|
||||
WebsiteRestoreRequest.from_manifest,
|
||||
restore_requested_website,
|
||||
limit=16 * 1024,
|
||||
)
|
||||
|
||||
|
||||
def restore_requested_website(request):
|
||||
if os.geteuid() != 0:
|
||||
raise ValueError(
|
||||
"Run restore-website-request as root on the backup node."
|
||||
)
|
||||
with locked_root_directory(RESTORE_DIRECTORY) as directory:
|
||||
claim = RESTORE_DIRECTORY / f"{request.restore_id}.json"
|
||||
result = claim.with_suffix(".result")
|
||||
manifest = json.dumps(request.manifest())
|
||||
try:
|
||||
write_new_file(claim, manifest, mode=0o600)
|
||||
except FileExistsError:
|
||||
if read_root_file(claim, mode=0o600) != manifest:
|
||||
raise ValueError(
|
||||
"This restore ID belongs to a different request."
|
||||
) from None
|
||||
if not result.exists():
|
||||
raise ValueError(
|
||||
"The previous restore was interrupted. "
|
||||
"Check the destination before requesting another restore."
|
||||
) from None
|
||||
problem = json.loads(read_root_file(result, mode=0o600))
|
||||
else:
|
||||
# Persist the claim before writing website files.
|
||||
os.fsync(directory)
|
||||
problem = None
|
||||
try:
|
||||
restore_website_from_bundle(request)
|
||||
except (OSError, ValueError) as error:
|
||||
problem = str(error)
|
||||
write_new_file(result, json.dumps(problem), mode=0o600)
|
||||
os.fsync(directory)
|
||||
if problem is not None:
|
||||
raise ValueError(problem)
|
||||
|
||||
|
||||
def restore_website_from_bundle(request):
|
||||
from .web_node_backup import restore_native_website
|
||||
|
||||
archive = backup_archive(request.site.account_id, request.backup_id)
|
||||
try:
|
||||
with (
|
||||
open_account_bundle(archive) as (bundle, backup),
|
||||
TemporaryDirectory(dir=RESTORE_DIRECTORY) as temporary,
|
||||
):
|
||||
if backup.website != request.site:
|
||||
raise ValueError("This backup is for a different website.")
|
||||
staged = Path(temporary) / "website.tar.gz"
|
||||
with (
|
||||
bundle.open(staged.name) as source,
|
||||
staged.open("xb") as target,
|
||||
):
|
||||
os.fchmod(target.fileno(), 0o600)
|
||||
copyfileobj(source, target, length=CHUNK_BYTES)
|
||||
restore_native_website(
|
||||
request.site,
|
||||
staged,
|
||||
filename=request.filename,
|
||||
replace=request.replace,
|
||||
)
|
||||
except FileNotFoundError as error:
|
||||
if error.filename == str(archive):
|
||||
raise ValueError(
|
||||
"The selected backup archive is no longer on disk."
|
||||
) from None
|
||||
raise
|
||||
except OSError as error:
|
||||
if error.errno == errno.EDQUOT:
|
||||
raise ValueError(
|
||||
"The restore exceeded a filesystem storage quota."
|
||||
) from None
|
||||
raise
|
||||
except BadZipFile:
|
||||
raise ValueError(
|
||||
"The selected account backup ZIP is unreadable."
|
||||
) from None
|
||||
@@ -264,7 +264,7 @@ class AccountBackupRequestTests(SimpleTestCase):
|
||||
)
|
||||
)
|
||||
self.enterContext(
|
||||
patch.object(account_backup_request, "require_root_directory")
|
||||
patch.object(account_backup_request, "locked_root_directory")
|
||||
)
|
||||
self.enterContext(
|
||||
patch.object(account_backup_request, "check_root_file")
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import os
|
||||
import stat
|
||||
from contextlib import contextmanager
|
||||
from tempfile import NamedTemporaryFile
|
||||
|
||||
|
||||
@@ -49,3 +50,16 @@ def write_new_file(path, content, *, mode, group=None):
|
||||
os.fchmod(staged.fileno(), mode)
|
||||
os.fsync(staged.fileno())
|
||||
os.link(staged.name, path)
|
||||
|
||||
|
||||
@contextmanager
|
||||
def locked_root_directory(path):
|
||||
import fcntl
|
||||
|
||||
require_root_directory(path)
|
||||
fd = os.open(path, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW)
|
||||
try:
|
||||
fcntl.flock(fd, fcntl.LOCK_EX)
|
||||
yield fd
|
||||
finally:
|
||||
os.close(fd)
|
||||
@@ -3,7 +3,7 @@ import json
|
||||
import os
|
||||
import stat
|
||||
import tarfile
|
||||
from contextlib import contextmanager
|
||||
from contextlib import ExitStack, contextmanager
|
||||
from io import BytesIO
|
||||
from pathlib import Path
|
||||
from tempfile import NamedTemporaryFile, TemporaryDirectory
|
||||
@@ -302,13 +302,11 @@ def publish_restored_file(staged, public, selected, uid, replace):
|
||||
|
||||
@contextmanager
|
||||
def open_restore_parent(fd, parts, uid):
|
||||
if not parts:
|
||||
with ExitStack() as opened:
|
||||
for part in parts:
|
||||
fd = opened.enter_context(open_directory(part, parent=fd))
|
||||
if os.fstat(fd).st_uid != uid:
|
||||
raise ValueError(
|
||||
"A directory in the restore path belongs to another user."
|
||||
)
|
||||
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
|
||||
Reference in new issue
Block a user