Add DirectAdmin backup inspection and account metadata import #9

Merged
parkel merged 3 commits from feature/directadmin-import into main 2026-11-21 00:03:45 +01:00
12 changed files with 1137 additions and 0 deletions

No files matched your search

+68
View File
@@ -336,6 +336,74 @@ installation needs attention.
Exit code `1` indicates an invalid manifest or an invocation error such as
running the check without root privileges.
## Inspect a DirectAdmin backup
Use an account archive from DirectAdmin's Site Backup, Manage User Backups
or Admin Backup/Transfer feature. Coulobre reads plain tar and gzip archives
directly. Install the `zstd` package to read Zstandard archives. See the
[DirectAdmin backup guide](https://docs.directadmin.com/directadmin/backup-restore-migration/).
```sh
coulobre-directadmin inspect user.admin.customer.tar.zst
```
The command reads the archive in place and prints a JSON inventory. It
reports the source account and primary domain, discovered domains, website
and mail file counts, DNS zone presence, supported mailbox addresses, and
database dump names. Mailboxes with names outside Coulobre's address format
are counted separately. It records the presence of a nested home archive.
Symbolic links, hard links and other special entries are counted separately
from regular files.
The inventory reads the account, domain and mailbox lists from their
metadata files and checks the rest by archive entry. These metadata files
have an 8 MiB limit per file. Mail and website counts refer to regular
files at recognized paths. The report contains names and counts rather
than passwords, hashes or file contents.
### Plan a DirectAdmin import
On the panel host, use the panel's database settings to preview which
account, mailbox requests and database requests can be created.
```sh
python manage.py plan_directadmin_import user.admin.customer.tar.zst
```
The plan uses the source username as the account name and picks the backup's
primary domain, or its only discovered domain when there is no default.
Use `--primary-domain` to select a different domain from the backup. For
a domainless archive, use it to assign the new account a domain.
The command reads the panel database and reports `blocked` when the chosen
domain is already assigned to a hosting account, DNS zone or mail domain,
or when a domain still needs to be selected. The report lists database
requests using the suffix after the source username and mailbox requests
for the selected domain. The `manual_review` list identifies other domains,
database names that need a mapping, and data that needs a separate migration,
including website files, DNS zones, mail files and SQL dumps.
### Import DirectAdmin account metadata
Apply the panel database migrations, then run the import on the panel host
with the backup and the same primary domain selection used for the preview.
```sh
python manage.py import_directadmin user.admin.customer.tar.zst
```
The import checks domain ownership again and creates the new hosting account,
supported database requests and selected domain's mailbox requests in one
transaction. The JSON report includes the new account ID and the MariaDB
names derived from the database requests. Use the account page to download
deployment manifests for the nodes. The `manual_review` list records the
website, DNS, mail and SQL data that needs a separate migration.
Replaying the same account and request selection reports `already_imported`
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
its report and exits with code `2`.
## Request an Apache configuration preview
Start RabbitMQ and set `COULOBRE_BROKER_URL` to its AMQP URL. The development
+1
View File
@@ -17,6 +17,7 @@ dependencies = [
[project.scripts]
coulobre-database-node = "coulobre.database_node:main"
coulobre-directadmin = "coulobre.directadmin:main"
coulobre-dns-node = "coulobre.dns_node:main"
coulobre-mail-node = "coulobre.mail_node:main"
coulobre-web-node = "coulobre.web_node:main"
+248
View File
@@ -0,0 +1,248 @@
import argparse
import gzip
import json
import re
import subprocess
import tarfile
import zlib
from contextlib import contextmanager
from dataclasses import dataclass, field
from pathlib import Path, PurePosixPath
from .domain_names import canonical_domain
from .mail_node import MailboxSpec
MAX_METADATA_SIZE = 8 * 1024 * 1024
ZSTD_MAGIC = b"\x28\xb5\x2f\xfd"
HOME_ARCHIVES = {"home.tar", "home.tar.gz", "home.tar.zst"}
class BackupTarInfo(tarfile.TarInfo):
@classmethod
def fromtarfile(cls, archive):
try:
return super().fromtarfile(archive)
except (tarfile.InvalidHeaderError, tarfile.SubsequentHeaderError):
raise tarfile.ReadError("Invalid backup tar header.") from None
@dataclass
class DomainInventory:
website_files: int = 0
dns_zone: bool = False
mailboxes: set[str] = field(default_factory=set)
mail_files: int = 0
unrecognized_mailbox_entries: int = 0
def report(self, name):
return {
"name": name,
"website_files": self.website_files,
"dns_zone": self.dns_zone,
"mailboxes": sorted(self.mailboxes),
"mail_files": self.mail_files,
"unrecognized_mailbox_entries": self.unrecognized_mailbox_entries,
}
@dataclass
class BackupInventory:
username: str | None = None
primary_domain: str | None = None
domains: dict[str, DomainInventory] = field(default_factory=dict)
databases: set[str] = field(default_factory=set)
home_archive: bool = False
skipped_non_regular_entries: int = 0
metadata_paths: set[tuple[str, ...]] = field(default_factory=set)
def domain(self, value):
inventory = self.domains.get(value)
if inventory is None:
inventory = self.domains.setdefault(
canonical_domain(value), DomainInventory()
)
return inventory
def visit(self, archive, member):
path = PurePosixPath(member.name)
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.isdir():
self.skipped_non_regular_entries += 1
return
match parts:
case ("backup", "user.conf"):
settings = read_account_settings(
self.read_metadata(archive, member, parts)
)
self.username = settings["username"]
if settings["domain"]:
self.primary_domain = canonical_domain(settings["domain"])
self.domain(self.primary_domain)
case ("backup", "domains.list"):
for line in self.read_metadata(archive, member, parts).splitlines():
if line.strip():
self.domain(line.strip())
case ("backup", filename):
if match := re.fullmatch(r"([a-zA-Z0-9_]{1,64})\.sql", filename):
self.databases.add(match[1])
if filename in HOME_ARCHIVES:
self.home_archive = True
case ("backup", domain, filename) if filename == f"{domain}.db":
self.domain(domain).dns_zone = True
case ("backup", domain, filename) if filename == f"{domain}.conf":
self.domain(domain)
case ("backup", domain, "email", "passwd"):
lines = self.read_metadata(archive, member, parts)
self.visit_mailboxes(domain, lines)
case ("backup", domain, "email", "data", "imap", *tail) if (
tail and tail != [".direct_imap_backup"]
):
self.domain(domain).mail_files += 1
case ("domains", domain, "public_html" | "private_html", *tail) if tail:
self.domain(domain).website_files += 1
case ("domains", domain, "domain.conf"):
self.domain(domain)
case ("imap", domain, *tail) if tail:
self.domain(domain).mail_files += 1
def read_metadata(self, archive, member, parts):
if parts in self.metadata_paths:
raise ValueError(
"The archive contains duplicate account or mailbox metadata."
)
self.metadata_paths.add(parts)
if not 0 <= member.size <= MAX_METADATA_SIZE:
raise ValueError(
"An account or mailbox metadata file exceeds the size limit."
)
with archive.extractfile(member) as stream:
return stream.read().decode("utf-8", errors="replace")
def visit_mailboxes(self, domain, text):
inventory = self.domain(domain)
for line in text.splitlines():
if not line.strip():
continue
local_part, separator, _ = line.partition(":")
try:
if not separator:
raise ValueError
mailbox = MailboxSpec(domain, local_part)
except ValueError:
inventory.unrecognized_mailbox_entries += 1
else:
inventory.mailboxes.add(mailbox.address)
def report(self):
if self.username is None:
raise ValueError(
"Expected a DirectAdmin account backup with backup/user.conf."
)
return {
"version": 1,
"kind": "directadmin_backup_inventory",
"username": self.username,
"primary_domain": self.primary_domain,
"domains": [
inventory.report(name)
for name, inventory in sorted(self.domains.items())
],
"databases": sorted(self.databases),
"home_archive": self.home_archive,
"skipped_non_regular_entries": self.skipped_non_regular_entries,
}
def read_account_settings(text):
settings = {}
for line in text.splitlines():
key, separator, value = line.partition("=")
if separator and key in {"username", "domain"}:
if key in settings:
raise ValueError("The account metadata repeats an identity field.")
settings[key] = value.strip()
username = settings.get("username", "")
if not re.fullmatch(r"[a-zA-Z0-9][a-zA-Z0-9_-]{0,31}", username):
raise ValueError(
"The account metadata is missing a valid DirectAdmin username."
)
return {"username": username, "domain": settings.get("domain")}
@contextmanager
def archive_stream(path):
with path.open("rb", buffering=0) as source:
magic = source.read(4)
source.seek(0)
if magic.startswith(b"\x1f\x8b"):
with gzip.GzipFile(fileobj=source) as stream:
yield stream
elif magic == ZSTD_MAGIC:
try:
decoder = subprocess.Popen(
["zstd", "--decompress", "--stdout", "--quiet"],
stdin=source,
stdout=subprocess.PIPE,
stderr=subprocess.DEVNULL,
)
except FileNotFoundError:
raise ValueError("Install zstd to inspect Zstandard backups.") from None
with decoder:
try:
yield decoder.stdout
except BaseException:
decoder.kill()
raise
if decoder.wait():
raise ValueError("The Zstandard backup is damaged or incomplete.")
else:
yield source
def check_tar_padding(archive):
size = 0
while chunk := archive.fileobj.read(64 * 1024):
if chunk.strip(b"\0"):
raise ValueError("Unexpected data after the end of the tar archive.")
size += len(chunk)
if size < tarfile.BLOCKSIZE:
raise ValueError("The tar archive is missing its end marker.")
def inspect_backup(path):
inventory = BackupInventory()
try:
with (
archive_stream(path) as stream,
tarfile.open(fileobj=stream, mode="r|", tarinfo=BackupTarInfo) as archive,
):
while (member := archive.next()) is not None:
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):
raise ValueError(
"The backup is not a readable or complete tar archive."
) from None
return inventory.report()
def main(argv=None):
parser = argparse.ArgumentParser(prog="coulobre-directadmin")
commands = parser.add_subparsers(dest="command", required=True)
inspect = commands.add_parser(
"inspect", help="Inventory a DirectAdmin account backup."
)
inspect.add_argument("backup", type=Path)
args = parser.parse_args(argv)
try:
report = inspect_backup(args.backup)
except (OSError, ValueError) as error:
parser.exit(1, f"coulobre-directadmin: {error}\n")
print(json.dumps(report, indent=2))
return 0
+261
View File
@@ -0,0 +1,261 @@
import hashlib
import json
import re
from collections import defaultdict
from django.db import IntegrityError, transaction
from coulobre.database_node import DATABASE_SUFFIX_PATTERN, DatabaseSpec
from coulobre.domain_names import canonical_domain
from .models import (
DirectAdminImport,
HostingAccount,
HostingDatabase,
HostingDnsZone,
HostingMailbox,
HostingMailDomain,
)
def plan_directadmin_import(inventory, primary_domain=None):
username = inventory["username"]
domains = {entry["name"]: entry for entry in inventory["domains"]}
if primary_domain is not None:
primary_domain = canonical_domain(primary_domain)
if domains and primary_domain not in domains:
raise ValueError("The selected primary domain is absent from the backup.")
else:
primary_domain = inventory["primary_domain"]
if primary_domain is None and len(domains) == 1:
primary_domain = next(iter(domains))
databases, review = plan_database_requests(username, inventory["databases"])
review.extend(review_backup_data(inventory, primary_domain))
account = None
conflicts = []
problems = []
if primary_domain is None:
problems.append("Select a primary domain for the hosting account.")
else:
account = {"name": username, "primary_domain": primary_domain}
conflicts = domain_conflicts(primary_domain)
return {
"version": 1,
"kind": "directadmin_import_plan",
"state": "blocked" if problems or conflicts else "ready",
"source_username": username,
"source_domains": list(domains),
"account": account,
"database_requests": databases,
"mailbox_requests": domains.get(primary_domain, {}).get("mailboxes", []),
"conflicts": conflicts,
"problems": problems,
"manual_review": review,
}
def plan_database_requests(username, sources):
by_suffix = defaultdict(list)
review = []
prefix = f"{username.lower()}_"
for source in sources:
normalized = source.lower()
suffix = normalized.removeprefix(prefix)
if normalized == suffix or not re.fullmatch(DATABASE_SUFFIX_PATTERN, suffix):
review.append(
{
"kind": "database_name",
"source": source,
"reason": "unsupported_suffix",
}
)
continue
by_suffix[suffix].append(source)
requests = []
for suffix, names in sorted(by_suffix.items()):
if len(names) == 1:
requests.append({"source": names[0], "suffix": suffix})
else:
review.append(
{
"kind": "database_name",
"sources": names,
"reason": "duplicate_suffix",
}
)
return requests, review
def review_backup_data(inventory, primary_domain):
entries = []
for domain in inventory["domains"]:
name = domain["name"]
if primary_domain is not None and name != primary_domain:
entries.append(
{
"kind": "additional_domain",
"domain": name,
"mailboxes": domain["mailboxes"],
}
)
if domain["dns_zone"]:
entries.append({"kind": "dns_zone", "domain": name})
for field in ("website_files", "mail_files", "unrecognized_mailbox_entries"):
if domain[field]:
entries.append({"kind": field, "domain": name, "count": domain[field]})
if inventory["databases"]:
entries.append({"kind": "database_dumps", "names": inventory["databases"]})
if inventory["home_archive"]:
entries.append({"kind": "nested_home_archive"})
if inventory["skipped_non_regular_entries"]:
entries.append(
{
"kind": "special_archive_entries",
"count": inventory["skipped_non_regular_entries"],
}
)
return entries
def domain_conflicts(domain):
sources = (
("hosting_account", HostingAccount, "primary_domain", "pk"),
("dns_zone", HostingDnsZone, "domain", "account_id"),
("mail_domain", HostingMailDomain, "domain", "account_id"),
)
conflicts = []
for kind, model, domain_field, owner_field in sources:
owner = (
model.objects.filter(**{domain_field: domain})
.values_list(owner_field, flat=True)
.first()
)
if owner is not None:
conflicts.append({"kind": kind, "domain": domain, "account_id": owner})
return conflicts
def import_directadmin_account(inventory, primary_domain=None):
plan = import_report(plan_directadmin_import(inventory, primary_domain))
if plan["account"] is None:
return plan
fingerprint = import_fingerprint(plan)
previous = previous_import(plan, fingerprint)
if previous is not None:
return previous
if plan["state"] == "blocked":
return plan
try:
with transaction.atomic():
account = HostingAccount.objects.create(**plan["account"])
conflicts = [
conflict
for conflict in domain_conflicts(account.primary_domain)
if conflict["account_id"] != account.pk
]
if conflicts:
transaction.set_rollback(True)
return plan | {"state": "blocked", "conflicts": conflicts}
HostingDatabase.objects.bulk_create(
HostingDatabase(account=account, suffix=request["suffix"])
for request in plan["database_requests"]
)
if plan["mailbox_requests"]:
mail_domain = HostingMailDomain.objects.create(
account=account, domain=account.primary_domain
)
HostingMailbox.objects.bulk_create(
HostingMailbox(
mail_domain=mail_domain, local_part=address.split("@", 1)[0]
)
for address in plan["mailbox_requests"]
)
DirectAdminImport.objects.create(account=account, fingerprint=fingerprint)
except IntegrityError:
# A different process may have claimed the domain while the plan was read.
refreshed = import_report(plan_directadmin_import(inventory, primary_domain))
previous = previous_import(refreshed, fingerprint)
if previous is not None:
return previous
if refreshed["state"] == "blocked":
return refreshed
raise
return completed_import(plan, account, "imported")
def import_report(plan):
return plan | {"kind": "directadmin_import_result"}
def import_fingerprint(plan):
identity = {
key: plan[key] for key in ("account", "database_requests", "mailbox_requests")
}
payload = json.dumps(identity, sort_keys=True).encode("utf-8")
return hashlib.sha256(payload).hexdigest()
def previous_import(plan, fingerprint):
saved = (
DirectAdminImport.objects.select_related("account")
.filter(fingerprint=fingerprint)
.first()
)
if saved is None:
return None
account = saved.account
domain = plan["account"]["primary_domain"]
conflicts = [
conflict
for conflict in plan["conflicts"]
if conflict["account_id"] != account.pk
]
if conflicts:
return plan | {"state": "blocked", "conflicts": conflicts}
if account.primary_domain != domain:
return plan | {
"state": "blocked",
"problems": ["The imported account now uses a different primary domain."],
}
suffixes = {request["suffix"] for request in plan["database_requests"]}
mailboxes = {address.split("@", 1)[0] for address in plan["mailbox_requests"]}
if not suffixes.issubset(account.databases.values_list("suffix", flat=True)) or (
mailboxes
and not mailboxes.issubset(
HostingMailbox.objects.filter(
mail_domain__account=account, mail_domain__domain=domain
).values_list("local_part", flat=True)
)
):
return plan | {
"state": "blocked",
"problems": [
"The imported account is missing one or more original requests."
],
}
return completed_import(plan, account, "already_imported")
def completed_import(plan, account, state):
return plan | {
"state": state,
"account": {
"id": account.pk,
"name": account.name,
"primary_domain": account.primary_domain,
},
"database_requests": [
request | {"database": DatabaseSpec(account.pk, request["suffix"]).name}
for request in plan["database_requests"]
],
"conflicts": [],
}
Whitespace-only changes.
Whitespace-only changes.
@@ -0,0 +1,34 @@
import json
from pathlib import Path
from django.core.management.base import BaseCommand, CommandError
from django.db import IntegrityError
from coulobre.directadmin import inspect_backup
from coulobre.hosting.directadmin_import import import_directadmin_account
class Command(BaseCommand):
help = (
"Create a hosting account and its supported requests from a DirectAdmin backup."
)
def add_arguments(self, parser):
parser.add_argument("backup", type=Path)
parser.add_argument(
"--primary-domain", help="Select the domain for the new account."
)
def handle(self, *args, **options):
try:
inventory = inspect_backup(options["backup"])
result = import_directadmin_account(inventory, options["primary_domain"])
except (OSError, ValueError) as error:
raise CommandError(str(error)) from None
except IntegrityError:
raise CommandError("The panel database rejected the import.") from None
self.stdout.write(json.dumps(result, indent=2))
if result["state"] == "blocked":
raise CommandError(
"The import is blocked. Review the report.", returncode=2
)
@@ -0,0 +1,25 @@
import json
from pathlib import Path
from django.core.management.base import BaseCommand, CommandError
from coulobre.directadmin import inspect_backup
from coulobre.hosting.directadmin_import import plan_directadmin_import
class Command(BaseCommand):
help = "Preview a DirectAdmin account import against the current panel database."
def add_arguments(self, parser):
parser.add_argument("backup", type=Path)
parser.add_argument(
"--primary-domain", help="Select the domain for the new account."
)
def handle(self, *args, **options):
try:
inventory = inspect_backup(options["backup"])
plan = plan_directadmin_import(inventory, options["primary_domain"])
except (OSError, ValueError) as error:
raise CommandError(str(error)) from None
self.stdout.write(json.dumps(plan, indent=2))
@@ -0,0 +1,36 @@
# Generated by Django 5.2.19 on 2026-11-20 22:30
import django.db.models.deletion
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("hosting", "0009_hostingdnszone_mail_records"),
]
operations = [
migrations.CreateModel(
name="DirectAdminImport",
fields=[
(
"id",
models.BigAutoField(
auto_created=True,
primary_key=True,
serialize=False,
verbose_name="ID",
),
),
("fingerprint", models.CharField(max_length=64, unique=True)),
(
"account",
models.OneToOneField(
on_delete=django.db.models.deletion.CASCADE,
related_name="directadmin_import",
to="hosting.hostingaccount",
),
),
],
),
]
+7
View File
@@ -90,6 +90,13 @@ class HostingDatabase(models.Model):
return self.spec.name
class DirectAdminImport(models.Model):
account = models.OneToOneField(
HostingAccount, on_delete=models.CASCADE, related_name="directadmin_import"
)
fingerprint = models.CharField(max_length=64, unique=True)
class HostingDnsZone(models.Model):
account = models.ForeignKey(
HostingAccount, on_delete=models.PROTECT, related_name="dns_zones"
+175
View File
@@ -0,0 +1,175 @@
import gzip
import json
import shutil
import subprocess
import tarfile
from contextlib import redirect_stderr, redirect_stdout
from io import BytesIO, StringIO
from pathlib import Path
from tempfile import TemporaryDirectory
from unittest import skipUnless
from unittest.mock import patch
from django.test import SimpleTestCase
from coulobre.directadmin import inspect_backup, main
def make_tar(entries):
output = BytesIO()
with tarfile.open(fileobj=output, mode="w") as archive:
for name, payload in entries:
member = tarfile.TarInfo(name)
if payload is None:
member.type = tarfile.SYMTYPE
member.linkname = "public_html"
archive.addfile(member)
else:
data = payload.encode("utf-8")
member.size = len(data)
archive.addfile(member, BytesIO(data))
return output.getvalue()
class DirectAdminInventoryTests(SimpleTestCase):
def setUp(self):
self.directory = Path(self.enterContext(TemporaryDirectory()))
self.entries = [
(
"./backup/user.conf",
"username=customer\npassword=private-account-hash\ndomain=Bücher.Example\n",
),
("backup/domains.list", "bücher.example\n"),
("backup/other.example/other.example.conf", "domain=other.example\n"),
(
"backup/xn--bcher-kva.example/email/passwd",
"Support:private-mail-hash:10\nold.value+tag:other-private-hash:10\n",
),
("backup/xn--bcher-kva.example/xn--bcher-kva.example.db", "; DNS zone"),
("backup/customer_wp.sql", "private database content"),
("backup/home.tar.gz", "nested home archive content"),
(
"domains/xn--bcher-kva.example/public_html/index.php",
"private website content",
),
("domains/xn--bcher-kva.example/private_html", None),
("imap/xn--bcher-kva.example/support/Maildir/cur/message", "private email"),
("backup/other.example/email/data/imap/Maildir/cur/message", "old Maildir"),
("backup/other.example/email/data/imap/.direct_imap_backup", ""),
]
def save(self, content, name="user.admin.customer.tar"):
path = self.directory / name
path.write_bytes(content)
return path
def test_inventory_describes_contents_without_emitting_private_payloads(self):
path = self.save(
gzip.compress(make_tar(self.entries)), "user.admin.customer.tar.gz"
)
output = self.enterContext(redirect_stdout(StringIO()))
self.assertEqual(main(["inspect", str(path)]), 0)
report = json.loads(output.getvalue())
self.assertEqual(report["username"], "customer")
self.assertEqual(report["primary_domain"], "xn--bcher-kva.example")
self.assertEqual(report["databases"], ["customer_wp"])
self.assertTrue(report["home_archive"])
self.assertEqual(report["skipped_non_regular_entries"], 1)
self.assertEqual(
report["domains"],
[
{
"name": "other.example",
"website_files": 0,
"dns_zone": False,
"mailboxes": [],
"mail_files": 1,
"unrecognized_mailbox_entries": 0,
},
{
"name": "xn--bcher-kva.example",
"website_files": 1,
"dns_zone": True,
"mailboxes": ["support@xn--bcher-kva.example"],
"mail_files": 1,
"unrecognized_mailbox_entries": 1,
},
],
)
self.assertNotIn("private", output.getvalue())
self.assertEqual(list(self.directory.iterdir()), [path])
def test_plain_tar_allows_a_backup_with_only_account_metadata(self):
path = self.save(make_tar([("backup/user.conf", "username=mailadmin\n")]))
report = inspect_backup(path)
self.assertEqual(report["username"], "mailadmin")
self.assertIsNone(report["primary_domain"])
self.assertEqual(report["domains"], [])
@skipUnless(shutil.which("zstd"), "zstd is required for Zstandard fixtures")
def test_zstandard_stream_uses_the_same_inventory_and_rejects_truncation(self):
tar = make_tar(self.entries)
compressed = subprocess.run(
["zstd", "--stdout", "--quiet"], input=tar, capture_output=True, check=True
).stdout
path = self.save(compressed, "user.admin.customer.tar.zst")
self.assertEqual(inspect_backup(path), inspect_backup(self.save(tar)))
path.write_bytes(compressed[:-1])
with self.assertRaisesRegex(ValueError, "backup|archive"):
inspect_backup(path)
def test_archive_requires_regular_and_unambiguous_account_metadata(self):
for entries, problem in (
([("backup/user.conf", None)], "Expected a DirectAdmin account backup"),
(
[*self.entries, ("backup/user.conf", "username=other\n")],
"duplicate account or mailbox metadata",
),
):
with (
self.subTest(problem=problem),
self.assertRaisesRegex(ValueError, problem),
):
inspect_backup(self.save(make_tar(entries)))
def test_rejects_oversized_metadata_without_printing_it(self):
path = self.save(make_tar(self.entries))
with (
patch("coulobre.directadmin.MAX_METADATA_SIZE", 4),
self.assertRaisesRegex(ValueError, "metadata file exceeds the size limit"),
):
inspect_backup(path)
def test_truncated_gzip_fails_before_emitting_an_inventory(self):
path = self.save(gzip.compress(make_tar(self.entries))[:-4])
output = self.enterContext(redirect_stdout(StringIO()))
errors = self.enterContext(redirect_stderr(StringIO()))
with self.assertRaises(SystemExit) as exit:
main(["inspect", str(path)])
self.assertEqual(exit.exception.code, 1)
self.assertEqual(output.getvalue(), "")
self.assertIn("not a readable or complete tar archive", errors.getvalue())
self.assertNotIn("private", errors.getvalue())
def test_plain_tar_requires_its_end_marker(self):
archive = make_tar([("backup/user.conf", "username=customer\n")])
self.assertGreater(len(archive), 3 * tarfile.BLOCKSIZE)
path = self.save(archive[: 3 * tarfile.BLOCKSIZE])
with self.assertRaisesRegex(ValueError, "missing its end marker"):
inspect_backup(path)
def test_invalid_header_does_not_end_an_otherwise_readable_tar(self):
archive = bytearray(make_tar([("backup/user.conf", "username=customer\n")]))
archive[2 * tarfile.BLOCKSIZE] = ord("x")
with self.assertRaisesRegex(
ValueError, "not a readable or complete tar archive"
):
inspect_backup(self.save(archive))
@@ -0,0 +1,282 @@
import json
from io import StringIO
from pathlib import Path
from tempfile import TemporaryDirectory
from unittest.mock import patch
from django.core.management import CommandError, call_command
from django.db import IntegrityError
from django.test import TestCase
from .models import (
DirectAdminImport,
HostingAccount,
HostingDatabase,
HostingDnsZone,
HostingMailbox,
HostingMailDomain,
)
from .test_directadmin import make_tar
class DirectAdminImportPlanTests(TestCase):
def setUp(self):
directory = Path(self.enterContext(TemporaryDirectory()))
self.backup = directory / "user.admin.client.tar"
self.entries = [
("backup/client_site.sql", "database dump"),
("backup/client_Store.sql", ""),
("backup/client_store.sql", ""),
("backup/client_9.sql", ""),
("backup/other_wp.sql", ""),
("backup/example.net/email/passwd", "support:private-mail-hash:10\n"),
("backup/other.example/email/passwd", "billing:private-other-hash:10\n"),
("backup/example.net/example.net.db", "zone file"),
("domains/example.net/public_html/index.php", "website data"),
("imap/example.net/support/Maildir/cur/message", "mail data"),
]
def write_backup(self, entries):
if entries is None:
entries = [
("backup/user.conf", "username=client\ndomain=Example.Net.\n"),
*self.entries,
]
self.backup.write_bytes(make_tar(entries))
def plan(self, entries=None, *, primary_domain=None):
self.write_backup(entries)
output = StringIO()
call_command(
"plan_directadmin_import",
self.backup,
primary_domain=primary_domain,
stdout=output,
)
return json.loads(output.getvalue())
def run_import(self, entries=None):
self.write_backup(entries)
self.import_output = StringIO()
call_command("import_directadmin", self.backup, stdout=self.import_output)
return json.loads(self.import_output.getvalue())
def test_command_reports_account_requests_and_manual_work_without_writing(self):
plan = self.plan()
self.assertEqual(plan["state"], "ready")
self.assertEqual(
plan["account"], {"name": "client", "primary_domain": "example.net"}
)
self.assertEqual(plan["source_domains"], ["example.net", "other.example"])
self.assertEqual(
plan["database_requests"], [{"source": "client_site", "suffix": "site"}]
)
self.assertEqual(plan["mailbox_requests"], ["support@example.net"])
for entry in (
{
"kind": "database_name",
"sources": ["client_Store", "client_store"],
"reason": "duplicate_suffix",
},
{
"kind": "database_name",
"source": "client_9",
"reason": "unsupported_suffix",
},
{
"kind": "database_name",
"source": "other_wp",
"reason": "unsupported_suffix",
},
{"kind": "dns_zone", "domain": "example.net"},
{"kind": "website_files", "domain": "example.net", "count": 1},
{"kind": "mail_files", "domain": "example.net", "count": 1},
{
"kind": "additional_domain",
"domain": "other.example",
"mailboxes": ["billing@other.example"],
},
):
with self.subTest(entry=entry):
self.assertIn(entry, plan["manual_review"])
self.assertFalse(HostingAccount.objects.exists())
self.assertFalse(HostingDatabase.objects.exists())
self.assertFalse(HostingMailDomain.objects.exists())
self.assertFalse(HostingMailbox.objects.exists())
def test_existing_account_blocks_the_plan(self):
account = HostingAccount.objects.create(
name="Existing", primary_domain="example.net"
)
plan = self.plan()
self.assertEqual(plan["state"], "blocked")
self.assertEqual(
plan["conflicts"],
[
{
"kind": "hosting_account",
"domain": "example.net",
"account_id": account.pk,
}
],
)
self.assertEqual(HostingAccount.objects.count(), 1)
def test_existing_dns_and_mail_ownership_block_a_reused_domain(self):
owner = HostingAccount.objects.create(
name="Renamed", primary_domain="renamed.example"
)
HostingDnsZone.objects.create(
account=owner,
domain="example.net",
nameservers=["ns1.provider.example"],
responsible_name="hostmaster.provider.example",
)
HostingMailDomain.objects.create(account=owner, domain="example.net")
plan = self.plan()
self.assertEqual(plan["state"], "blocked")
self.assertEqual(
plan["conflicts"],
[
{"kind": "dns_zone", "domain": "example.net", "account_id": owner.pk},
{
"kind": "mail_domain",
"domain": "example.net",
"account_id": owner.pk,
},
],
)
def test_multiple_domains_without_a_default_require_a_selection(self):
entries = [("backup/user.conf", "username=client\n"), *self.entries]
blocked = self.plan(entries)
self.assertEqual(blocked["state"], "blocked")
self.assertIsNone(blocked["account"])
self.assertTrue(blocked["problems"])
selected = self.plan(entries, primary_domain="Other.Example.")
self.assertEqual(selected["state"], "ready")
self.assertEqual(selected["account"]["primary_domain"], "other.example")
self.assertEqual(selected["mailbox_requests"], ["billing@other.example"])
with self.assertRaisesRegex(CommandError, "absent from the backup"):
self.plan(entries, primary_domain="absent.example")
def test_single_discovered_domain_or_explicit_new_domain_can_be_used(self):
account = ("backup/user.conf", "username=client\n")
discovered = self.plan([account, ("backup/domains.list", "example.net\n")])
assigned = self.plan([account], primary_domain="new.example")
self.assertEqual(discovered["account"]["primary_domain"], "example.net")
self.assertEqual(assigned["account"]["primary_domain"], "new.example")
def test_import_creates_planned_requests_and_reuses_the_same_account_on_replay(
self,
):
first = self.run_import()
replay = self.run_import()
self.assertEqual(first["kind"], "directadmin_import_result")
self.assertEqual(first["state"], "imported")
self.assertEqual(replay, first | {"state": "already_imported"})
account = HostingAccount.objects.get()
self.assertEqual(
first["account"],
{
"id": account.pk,
"name": "client",
"primary_domain": "example.net",
},
)
database = account.databases.get()
self.assertEqual(
first["database_requests"],
[
{
"source": "client_site",
"suffix": "site",
"database": database.spec.name,
},
],
)
self.assertEqual(
account.mail_domains.get().mailboxes.get().spec.address,
"support@example.net",
)
self.assertEqual(first["mailbox_requests"], ["support@example.net"])
self.assertEqual(DirectAdminImport.objects.get().account_id, account.pk)
self.assertFalse(HostingDnsZone.objects.exists())
self.assertNotIn("private-mail-hash", self.import_output.getvalue())
def test_import_refuses_to_merge_with_an_existing_hosting_account(self):
existing = HostingAccount.objects.create(
name="Existing", primary_domain="example.net"
)
with self.assertRaises(CommandError) as error:
self.run_import()
self.assertEqual(error.exception.returncode, 2)
result = json.loads(self.import_output.getvalue())
self.assertEqual(result["state"], "blocked")
self.assertEqual(result["conflicts"][0]["account_id"], existing.pk)
self.assertEqual(HostingAccount.objects.get().name, "Existing")
self.assertFalse(DirectAdminImport.objects.exists())
self.assertFalse(HostingDatabase.objects.exists())
def test_failed_import_rolls_back_all_requests(self):
with (
patch(
"coulobre.hosting.directadmin_import.HostingMailbox.objects.bulk_create",
side_effect=IntegrityError("Interrupted while saving mailboxes."),
),
self.assertRaisesRegex(CommandError, "database rejected the import"),
):
self.run_import()
for model in (
HostingAccount,
HostingDatabase,
HostingMailDomain,
HostingMailbox,
DirectAdminImport,
):
with self.subTest(model=model.__name__):
self.assertFalse(model.objects.exists())
self.assertEqual(self.run_import()["state"], "imported")
def test_conflict_discovered_during_import_rolls_back_the_new_account(self):
conflict = {"kind": "dns_zone", "domain": "example.net", "account_id": 99}
with (
patch(
"coulobre.hosting.directadmin_import.domain_conflicts",
side_effect=[[], [conflict]],
),
self.assertRaises(CommandError) as error,
):
self.run_import()
self.assertEqual(error.exception.returncode, 2)
self.assertEqual(
json.loads(self.import_output.getvalue())["conflicts"], [conflict]
)
self.assertFalse(HostingAccount.objects.exists())
def test_replay_reports_missing_requests_without_restoring_them(self):
self.run_import()
HostingDatabase.objects.get().delete()
with self.assertRaises(CommandError) as error:
self.run_import()
self.assertEqual(error.exception.returncode, 2)
result = json.loads(self.import_output.getvalue())
self.assertIn("missing one or more original requests", result["problems"][0])
self.assertFalse(HostingDatabase.objects.exists())
self.assertEqual(HostingAccount.objects.count(), 1)