Stage website files from DirectAdmin backups
This commit is contained in:
1 parent
c6310b1525
commit
2b4895df4f
5 files changed
+321
-12
No files matched your search
@@ -404,6 +404,22 @@ for the original account. A domain conflict or a change to the original
|
|||||||
account's domain or requests can block the import. A blocked import prints
|
account's domain or requests can block the import. A blocked import prints
|
||||||
its report and exits with code `2`.
|
its report and exits with code `2`.
|
||||||
|
|
||||||
|
### Stage DirectAdmin website files
|
||||||
|
|
||||||
|
Run the following command with a path for a new directory. The command
|
||||||
|
publishes the selected site's files under `document-root` inside that
|
||||||
|
directory after successfully reading the backup.
|
||||||
|
|
||||||
|
```sh
|
||||||
|
coulobre-directadmin stage-website user.admin.customer.tar.zst example.net ./example-net-stage
|
||||||
|
```
|
||||||
|
|
||||||
|
The default source is the domain's `public_html` directory. Use
|
||||||
|
`--source-root private_html` for a separate HTTPS document root. The
|
||||||
|
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.
|
||||||
|
|
||||||
## Request an Apache configuration preview
|
## Request an Apache configuration preview
|
||||||
|
|
||||||
Start RabbitMQ and set `COULOBRE_BROKER_URL` to its AMQP URL. The development
|
Start RabbitMQ and set `COULOBRE_BROKER_URL` to its AMQP URL. The development
|
||||||
|
|||||||
+41
-11
@@ -15,6 +15,7 @@ from .mail_node import MailboxSpec
|
|||||||
MAX_METADATA_SIZE = 8 * 1024 * 1024
|
MAX_METADATA_SIZE = 8 * 1024 * 1024
|
||||||
ZSTD_MAGIC = b"\x28\xb5\x2f\xfd"
|
ZSTD_MAGIC = b"\x28\xb5\x2f\xfd"
|
||||||
HOME_ARCHIVES = {"home.tar", "home.tar.gz", "home.tar.zst"}
|
HOME_ARCHIVES = {"home.tar", "home.tar.gz", "home.tar.zst"}
|
||||||
|
DOCUMENT_ROOTS = ("public_html", "private_html")
|
||||||
|
|
||||||
|
|
||||||
class BackupTarInfo(tarfile.TarInfo):
|
class BackupTarInfo(tarfile.TarInfo):
|
||||||
@@ -64,10 +65,7 @@ class BackupInventory:
|
|||||||
return inventory
|
return inventory
|
||||||
|
|
||||||
def visit(self, archive, member):
|
def visit(self, archive, member):
|
||||||
path = PurePosixPath(member.name)
|
parts = member_path(member)
|
||||||
parts = path.parts
|
|
||||||
if path.is_absolute() or ".." in parts:
|
|
||||||
raise ValueError("The archive contains an unsafe member path.")
|
|
||||||
if not member.isreg():
|
if not member.isreg():
|
||||||
if not member.isdir():
|
if not member.isdir():
|
||||||
self.skipped_non_regular_entries += 1
|
self.skipped_non_regular_entries += 1
|
||||||
@@ -213,22 +211,40 @@ def check_tar_padding(archive):
|
|||||||
raise ValueError("The tar archive is missing its end marker.")
|
raise ValueError("The tar archive is missing its end marker.")
|
||||||
|
|
||||||
|
|
||||||
def inspect_backup(path):
|
def member_path(member):
|
||||||
inventory = BackupInventory()
|
path = PurePosixPath(member.name)
|
||||||
|
if path.is_absolute() or ".." in path.parts:
|
||||||
|
raise ValueError("The archive contains an unsafe member path.")
|
||||||
|
return path.parts
|
||||||
|
|
||||||
|
|
||||||
|
@contextmanager
|
||||||
|
def open_backup(path):
|
||||||
try:
|
try:
|
||||||
with (
|
with (
|
||||||
archive_stream(path) as stream,
|
archive_stream(path) as stream,
|
||||||
tarfile.open(fileobj=stream, mode="r|", tarinfo=BackupTarInfo) as archive,
|
tarfile.open(fileobj=stream, mode="r|", tarinfo=BackupTarInfo) as archive,
|
||||||
):
|
):
|
||||||
while (member := archive.next()) is not None:
|
yield archive
|
||||||
inventory.visit(archive, member)
|
|
||||||
# The reader only walks forward and does not need tarfile's member cache.
|
|
||||||
archive.members.clear()
|
|
||||||
check_tar_padding(archive)
|
|
||||||
except (EOFError, tarfile.TarError, zlib.error, gzip.BadGzipFile):
|
except (EOFError, tarfile.TarError, zlib.error, gzip.BadGzipFile):
|
||||||
raise ValueError(
|
raise ValueError(
|
||||||
"The backup is not a readable or complete tar archive."
|
"The backup is not a readable or complete tar archive."
|
||||||
) from None
|
) from None
|
||||||
|
|
||||||
|
|
||||||
|
def backup_members(archive):
|
||||||
|
while (member := archive.next()) is not None:
|
||||||
|
yield member
|
||||||
|
# The reader only walks forward and does not need tarfile's member cache.
|
||||||
|
archive.members.clear()
|
||||||
|
check_tar_padding(archive)
|
||||||
|
|
||||||
|
|
||||||
|
def inspect_backup(path):
|
||||||
|
inventory = BackupInventory()
|
||||||
|
with open_backup(path) as archive:
|
||||||
|
for member in backup_members(archive):
|
||||||
|
inventory.visit(archive, member)
|
||||||
return inventory.report()
|
return inventory.report()
|
||||||
|
|
||||||
|
|
||||||
@@ -239,8 +255,22 @@ def main(argv=None):
|
|||||||
"inspect", help="Inventory a DirectAdmin account backup."
|
"inspect", help="Inventory a DirectAdmin account backup."
|
||||||
)
|
)
|
||||||
inspect.add_argument("backup", type=Path)
|
inspect.add_argument("backup", type=Path)
|
||||||
|
stage = commands.add_parser(
|
||||||
|
"stage-website", help="Stage one DirectAdmin website in a new local directory."
|
||||||
|
)
|
||||||
|
stage.add_argument("backup", type=Path)
|
||||||
|
stage.add_argument("domain")
|
||||||
|
stage.add_argument("destination", type=Path)
|
||||||
|
stage.add_argument("--source-root", choices=DOCUMENT_ROOTS, default="public_html")
|
||||||
args = parser.parse_args(argv)
|
args = parser.parse_args(argv)
|
||||||
try:
|
try:
|
||||||
|
if args.command == "stage-website":
|
||||||
|
from .directadmin_website import stage_website
|
||||||
|
|
||||||
|
report = stage_website(
|
||||||
|
args.backup, args.domain, args.destination, source_root=args.source_root
|
||||||
|
)
|
||||||
|
else:
|
||||||
report = inspect_backup(args.backup)
|
report = inspect_backup(args.backup)
|
||||||
except (OSError, ValueError) as error:
|
except (OSError, ValueError) as error:
|
||||||
parser.exit(1, f"coulobre-directadmin: {error}\n")
|
parser.exit(1, f"coulobre-directadmin: {error}\n")
|
||||||
|
|||||||
@@ -0,0 +1,104 @@
|
|||||||
|
import os
|
||||||
|
from contextlib import suppress
|
||||||
|
from pathlib import Path
|
||||||
|
from shutil import copyfileobj
|
||||||
|
from tempfile import TemporaryDirectory
|
||||||
|
|
||||||
|
from .directadmin import (
|
||||||
|
DOCUMENT_ROOTS,
|
||||||
|
BackupInventory,
|
||||||
|
backup_members,
|
||||||
|
member_path,
|
||||||
|
open_backup,
|
||||||
|
)
|
||||||
|
from .domain_names import canonical_domain
|
||||||
|
|
||||||
|
|
||||||
|
def stage_website(backup, domain, destination, *, source_root="public_html"):
|
||||||
|
domain = canonical_domain(domain)
|
||||||
|
if source_root not in DOCUMENT_ROOTS:
|
||||||
|
raise ValueError("Choose public_html or private_html from the backup.")
|
||||||
|
|
||||||
|
destination.mkdir(mode=0o700)
|
||||||
|
document_root = destination / "document-root"
|
||||||
|
try:
|
||||||
|
with TemporaryDirectory(dir=destination, prefix=".staging-") as directory:
|
||||||
|
staged = Path(directory) / "document-root"
|
||||||
|
staged.mkdir(mode=0o700)
|
||||||
|
summary = copy_website(backup, domain, source_root, staged)
|
||||||
|
staged.rename(document_root)
|
||||||
|
except BaseException:
|
||||||
|
with suppress(OSError):
|
||||||
|
destination.rmdir()
|
||||||
|
raise
|
||||||
|
return {
|
||||||
|
"version": 1,
|
||||||
|
"kind": "directadmin_website_stage",
|
||||||
|
"domain": domain,
|
||||||
|
"source_root": source_root,
|
||||||
|
"document_root": str(document_root),
|
||||||
|
**summary,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def copy_website(backup, domain, source_root, destination):
|
||||||
|
account = BackupInventory()
|
||||||
|
matches = {}
|
||||||
|
source_name = None
|
||||||
|
found_root = False
|
||||||
|
files = total_bytes = skipped = 0
|
||||||
|
with open_backup(backup) as archive:
|
||||||
|
for member in backup_members(archive):
|
||||||
|
parts = member_path(member)
|
||||||
|
if parts == ("backup", "user.conf"):
|
||||||
|
account.visit(archive, member)
|
||||||
|
if len(parts) < 3 or parts[0] != "domains" or parts[2] != source_root:
|
||||||
|
continue
|
||||||
|
name = parts[1]
|
||||||
|
if name not in matches:
|
||||||
|
matches[name] = canonical_domain(name) == domain
|
||||||
|
if not matches[name]:
|
||||||
|
continue
|
||||||
|
if source_name is not None and name != source_name:
|
||||||
|
raise ValueError(
|
||||||
|
"The backup contains multiple source directories for this domain."
|
||||||
|
)
|
||||||
|
source_name = name
|
||||||
|
|
||||||
|
target = destination.joinpath(*parts[3:])
|
||||||
|
if member.isdir():
|
||||||
|
target.mkdir(parents=True, exist_ok=True)
|
||||||
|
found_root = True
|
||||||
|
elif member.isreg():
|
||||||
|
if len(parts) == 3:
|
||||||
|
raise ValueError("The selected website document root is a file.")
|
||||||
|
copy_member(archive, member, target)
|
||||||
|
found_root = True
|
||||||
|
files += 1
|
||||||
|
total_bytes += member.size
|
||||||
|
else:
|
||||||
|
skipped += 1
|
||||||
|
|
||||||
|
if account.username is None:
|
||||||
|
raise ValueError("Expected a DirectAdmin account backup with backup/user.conf.")
|
||||||
|
if not found_root:
|
||||||
|
raise ValueError(
|
||||||
|
"The backup does not contain the selected website document root."
|
||||||
|
)
|
||||||
|
return {
|
||||||
|
"source_username": account.username,
|
||||||
|
"files": files,
|
||||||
|
"bytes": total_bytes,
|
||||||
|
"skipped_non_regular_entries": skipped,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def copy_member(archive, member, target):
|
||||||
|
if member.size < 0:
|
||||||
|
raise ValueError("A website file has an invalid size in the archive.")
|
||||||
|
target.parent.mkdir(parents=True, exist_ok=True)
|
||||||
|
with target.open("xb") as output, archive.extractfile(member) as source:
|
||||||
|
os.fchmod(output.fileno(), 0o600)
|
||||||
|
copyfileobj(source, output, length=1024 * 1024)
|
||||||
|
if output.tell() != member.size:
|
||||||
|
raise ValueError("A website file in the archive is incomplete.")
|
||||||
@@ -25,7 +25,7 @@ def make_tar(entries):
|
|||||||
member.linkname = "public_html"
|
member.linkname = "public_html"
|
||||||
archive.addfile(member)
|
archive.addfile(member)
|
||||||
else:
|
else:
|
||||||
data = payload.encode("utf-8")
|
data = payload.encode("utf-8") if isinstance(payload, str) else payload
|
||||||
member.size = len(data)
|
member.size = len(data)
|
||||||
archive.addfile(member, BytesIO(data))
|
archive.addfile(member, BytesIO(data))
|
||||||
return output.getvalue()
|
return output.getvalue()
|
||||||
|
|||||||
@@ -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 django.test import SimpleTestCase
|
||||||
|
|
||||||
|
from coulobre.directadmin import main
|
||||||
|
from coulobre.directadmin_website import stage_website
|
||||||
|
|
||||||
|
from .test_directadmin import make_tar
|
||||||
|
|
||||||
|
|
||||||
|
class DirectAdminWebsiteTests(SimpleTestCase):
|
||||||
|
def setUp(self):
|
||||||
|
directory = Path(self.enterContext(TemporaryDirectory()))
|
||||||
|
self.backup = directory / "client.tar.gz"
|
||||||
|
self.destination = directory / "site"
|
||||||
|
self.entries = [
|
||||||
|
("backup/user.conf", "username=client\ndomain=bücher.example\n"),
|
||||||
|
("./domains/Bücher.Example/public_html/index.php", "demo PHP source"),
|
||||||
|
("domains/Bücher.Example/public_html/.htaccess", "demo configuration"),
|
||||||
|
("domains/Bücher.Example/public_html/assets/example.bin", b"\x00\xff\x12"),
|
||||||
|
("domains/Bücher.Example/public_html/assets/site-link", None),
|
||||||
|
("domains/Bücher.Example/private_html/index.html", "private document root"),
|
||||||
|
("domains/other.example/public_html/index.html", "another site's data"),
|
||||||
|
]
|
||||||
|
|
||||||
|
def write_backup(self, entries):
|
||||||
|
self.backup.write_bytes(gzip.compress(make_tar(entries)))
|
||||||
|
|
||||||
|
def test_stage_command_copies_one_selected_website_into_a_private_directory(self):
|
||||||
|
self.write_backup(self.entries)
|
||||||
|
output = self.enterContext(redirect_stdout(StringIO()))
|
||||||
|
self.assertEqual(
|
||||||
|
main(
|
||||||
|
[
|
||||||
|
"stage-website",
|
||||||
|
str(self.backup),
|
||||||
|
"BÜCHER.example.",
|
||||||
|
str(self.destination),
|
||||||
|
]
|
||||||
|
),
|
||||||
|
0,
|
||||||
|
)
|
||||||
|
|
||||||
|
report = json.loads(output.getvalue())
|
||||||
|
document_root = self.destination / "document-root"
|
||||||
|
self.assertEqual(list(self.destination.iterdir()), [document_root])
|
||||||
|
self.assertEqual(report["domain"], "xn--bcher-kva.example")
|
||||||
|
self.assertEqual(report["source_username"], "client")
|
||||||
|
self.assertEqual(report["files"], 3)
|
||||||
|
self.assertEqual(report["bytes"], 36)
|
||||||
|
self.assertEqual(report["skipped_non_regular_entries"], 1)
|
||||||
|
self.assertEqual(report["document_root"], str(document_root))
|
||||||
|
self.assertEqual((document_root / "index.php").read_text(), "demo PHP source")
|
||||||
|
self.assertEqual(
|
||||||
|
(document_root / "assets/example.bin").read_bytes(), b"\x00\xff\x12"
|
||||||
|
)
|
||||||
|
self.assertTrue((document_root / ".htaccess").is_file())
|
||||||
|
self.assertFalse((document_root / "assets/site-link").is_symlink())
|
||||||
|
self.assertFalse((document_root / "index.html").exists())
|
||||||
|
self.assertEqual(stat.S_IMODE(self.destination.stat().st_mode), 0o700)
|
||||||
|
self.assertEqual(
|
||||||
|
stat.S_IMODE((document_root / "index.php").stat().st_mode), 0o600
|
||||||
|
)
|
||||||
|
self.assertNotIn("demo PHP source", output.getvalue())
|
||||||
|
|
||||||
|
def test_private_html_can_be_selected_explicitly(self):
|
||||||
|
self.write_backup(self.entries)
|
||||||
|
|
||||||
|
report = stage_website(
|
||||||
|
self.backup, "bücher.example", self.destination, source_root="private_html"
|
||||||
|
)
|
||||||
|
|
||||||
|
self.assertEqual(report["source_root"], "private_html")
|
||||||
|
self.assertEqual(
|
||||||
|
(Path(report["document_root"]) / "index.html").read_text(),
|
||||||
|
"private document root",
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_stage_does_not_replace_an_existing_destination(self):
|
||||||
|
self.write_backup(self.entries)
|
||||||
|
self.destination.mkdir()
|
||||||
|
existing = self.destination / "existing.txt"
|
||||||
|
existing.write_text("existing content")
|
||||||
|
|
||||||
|
with self.assertRaises(FileExistsError):
|
||||||
|
stage_website(self.backup, "bücher.example", self.destination)
|
||||||
|
|
||||||
|
self.assertEqual(list(self.destination.iterdir()), [existing])
|
||||||
|
self.assertEqual(existing.read_text(), "existing content")
|
||||||
|
|
||||||
|
def test_incomplete_archive_does_not_publish_a_document_root(self):
|
||||||
|
self.write_backup(self.entries)
|
||||||
|
self.backup.write_bytes(self.backup.read_bytes()[:-4])
|
||||||
|
|
||||||
|
with self.assertRaisesRegex(
|
||||||
|
ValueError, "not a readable or complete tar archive"
|
||||||
|
):
|
||||||
|
stage_website(self.backup, "bücher.example", self.destination)
|
||||||
|
|
||||||
|
self.assertFalse(self.destination.exists())
|
||||||
|
|
||||||
|
def test_canonical_domains_cannot_select_two_distinct_source_directories(self):
|
||||||
|
self.write_backup(
|
||||||
|
[
|
||||||
|
*self.entries,
|
||||||
|
(
|
||||||
|
"domains/xn--bcher-kva.example/public_html/second.php",
|
||||||
|
"another source directory",
|
||||||
|
),
|
||||||
|
]
|
||||||
|
)
|
||||||
|
|
||||||
|
with self.assertRaisesRegex(ValueError, "multiple source directories"):
|
||||||
|
stage_website(self.backup, "bücher.example", self.destination)
|
||||||
|
|
||||||
|
self.assertFalse(self.destination.exists())
|
||||||
|
|
||||||
|
def test_duplicate_website_members_do_not_overwrite_or_publish_files(self):
|
||||||
|
self.write_backup([*self.entries, self.entries[1]])
|
||||||
|
|
||||||
|
with self.assertRaises(FileExistsError):
|
||||||
|
stage_website(self.backup, "bücher.example", self.destination)
|
||||||
|
|
||||||
|
self.assertFalse(self.destination.exists())
|
||||||
|
|
||||||
|
def test_document_root_cannot_be_a_regular_file(self):
|
||||||
|
self.write_backup(
|
||||||
|
[
|
||||||
|
("backup/user.conf", "username=client\ndomain=example.net\n"),
|
||||||
|
("domains/example.net/public_html", "unexpected file"),
|
||||||
|
]
|
||||||
|
)
|
||||||
|
|
||||||
|
with self.assertRaisesRegex(ValueError, "document root is a file"):
|
||||||
|
stage_website(self.backup, "example.net", self.destination)
|
||||||
|
|
||||||
|
self.assertFalse(self.destination.exists())
|
||||||
|
|
||||||
|
def test_explicit_empty_document_root_is_available_for_staging(self):
|
||||||
|
with tarfile.open(self.backup, mode="w:gz") as archive:
|
||||||
|
payload = b"username=client\ndomain=example.net\n"
|
||||||
|
settings = tarfile.TarInfo("backup/user.conf")
|
||||||
|
settings.size = len(payload)
|
||||||
|
archive.addfile(settings, BytesIO(payload))
|
||||||
|
root = tarfile.TarInfo("domains/example.net/public_html")
|
||||||
|
root.type = tarfile.DIRTYPE
|
||||||
|
archive.addfile(root)
|
||||||
|
|
||||||
|
report = stage_website(self.backup, "example.net", self.destination)
|
||||||
|
|
||||||
|
self.assertEqual(report["files"], 0)
|
||||||
|
self.assertEqual(list(Path(report["document_root"]).iterdir()), [])
|
||||||
Reference in new issue
Block a user