Apply consistent Python and Django coding standards

This commit is contained in:
parkel committed 2026-11-21 02:12:32 +01:00
1 parent 1d0b5adeee
commit d7314fa927
61 files changed
+1829 -603

No files matched your search

+8 -2
View File
@@ -23,7 +23,7 @@ coulobre-mail-node = "coulobre.mail_node:main"
coulobre-web-node = "coulobre.web_node:main"
[project.optional-dependencies]
dev = ["ruff>=0.11,<1"]
dev = ["ruff==0.17.6"]
mariadb = ["mysqlclient>=2.2.1,<3"]
server = ["gunicorn>=27.0.1,<28"]
@@ -38,6 +38,12 @@ server = ["gunicorn>=27.0.1,<28"]
[tool.ruff]
target-version = "py312"
line-length = 79
[tool.ruff.lint]
select = ["E4", "E7", "E9", "F", "I"]
select = ["B", "DJ", "E", "F", "I", "N", "RUF100", "SIM", "UP", "W"]
# Internal records only need a string representation when displayed to users.
ignore = ["DJ008"]
[tool.ruff.lint.pycodestyle]
max-doc-length = 72
+17 -5
View File
@@ -11,7 +11,8 @@ MANIFEST_KIND = "mariadb_database"
DEFAULT_SOCKET = Path("/run/mysqld/mysqld.sock")
DATABASE_SUFFIX_PATTERN = r"\A[a-z][a-z0-9_]{0,23}\Z"
INVALID_SUFFIX = (
"Use 1 to 24 lowercase letters, digits, or underscores. Start with a letter."
"Use 1 to 24 lowercase letters, digits, or underscores. "
"Start with a letter."
)
@@ -21,8 +22,13 @@ class DatabaseSpec:
suffix: str
def __post_init__(self):
if type(self.account_id) is not int or not 1 <= self.account_id <= 2**63 - 1:
raise ValueError("The account ID must be a positive 64-bit integer.")
if (
type(self.account_id) is not int
or not 1 <= self.account_id <= 2**63 - 1
):
raise ValueError(
"The account ID must be a positive 64-bit integer."
)
if not isinstance(self.suffix, str) or not re.fullmatch(
DATABASE_SUFFIX_PATTERN, self.suffix
):
@@ -49,7 +55,10 @@ class DatabaseSpec:
"suffix",
}:
raise ValueError("Expected a MariaDB database manifest.")
if type(data["version"]) is not int or data["version"] != MANIFEST_VERSION:
if (
type(data["version"]) is not int
or data["version"] != MANIFEST_VERSION
):
raise ValueError("Unsupported database manifest version.")
if data["kind"] != MANIFEST_KIND:
raise ValueError("Expected a MariaDB database manifest.")
@@ -105,7 +114,10 @@ def main(argv=None):
return 0 if report["state"] == "configured" else 2
else:
print(
json.dumps({"database": database.name, "user": database.name}, indent=2)
json.dumps(
{"database": database.name, "user": database.name},
indent=2,
)
)
except (OSError, ValueError) as error:
parser.exit(1, f"coulobre-database-node: {error}\n")
+62 -27
View File
@@ -2,7 +2,7 @@ import hashlib
import json
import os
import secrets
from contextlib import closing, contextmanager
from contextlib import closing, contextmanager, suppress
from pathlib import Path
from .node_files import read_root_file, require_root_directory, write_new_file
@@ -46,25 +46,35 @@ def locked_cursor(database, socket):
) as connection,
closing(connection.cursor()) as cursor,
):
cursor.execute("SELECT GET_LOCK(%s, 10)", (f"coulobre:{database.name}",))
cursor.execute(
"SELECT GET_LOCK(%s, 10)", (f"coulobre:{database.name}",)
)
if cursor.fetchone() != (1,):
raise ValueError(
"Could not acquire the lock for this MariaDB database."
)
yield MySQLdb, cursor
except MySQLdb.Error as error:
code = error.args[0] if error.args and type(error.args[0]) is int else "unknown"
raise ValueError(f"MariaDB rejected the operation (error {code}).") from None
code = (
error.args[0]
if error.args and type(error.args[0]) is int
else "unknown"
)
raise ValueError(
f"MariaDB rejected the operation (error {code})."
) from None
def read_resources(cursor, name):
cursor.execute(
"SELECT SCHEMA_COMMENT FROM information_schema.SCHEMATA WHERE SCHEMA_NAME = %s",
"SELECT SCHEMA_COMMENT FROM information_schema.SCHEMATA "
"WHERE SCHEMA_NAME = %s",
(name,),
)
schema = cursor.fetchone()
cursor.execute(
"SELECT Host, plugin, authentication_string FROM mysql.user WHERE User = %s",
"SELECT Host, plugin, authentication_string FROM mysql.user "
"WHERE User = %s",
(name,),
)
return schema, cursor.fetchall()
@@ -78,7 +88,9 @@ def database_status(database, socket):
record_path = STATE_DIRECTORY / f"{database.name}.json"
with locked_cursor(database, socket) as (driver, cursor):
try:
state = check_database(driver, cursor, database, socket, record_path)
state = check_database(
driver, cursor, database, socket, record_path
)
problem = None
except (OSError, ValueError) as error:
state = "needs_attention"
@@ -95,14 +107,13 @@ def check_database(driver, cursor, database, socket, record_path):
name = database.name
schema, users = read_resources(cursor, name)
ready_path = record_path.with_suffix(".ready")
try:
with suppress(FileNotFoundError):
require_root_directory(record_path.parent)
except FileNotFoundError:
pass
if not os.path.lexists(record_path):
if os.path.lexists(ready_path) or schema is not None or users:
raise ValueError(
"The database, login, or completion marker has no local credentials record."
"The database, login, or completion marker has no local "
"credentials record."
)
return "not_installed"
@@ -120,7 +131,10 @@ def check_database(driver, cursor, database, socket, record_path):
cursor.execute("SHOW GRANTS FOR %s@'localhost'", (name,))
grantee = f"`{name}`@`localhost`"
expected_grants = {
(f"GRANT USAGE ON *.* TO {grantee} IDENTIFIED BY PASSWORD '{password_hash}'",),
(
f"GRANT USAGE ON *.* TO {grantee} "
f"IDENTIFIED BY PASSWORD '{password_hash}'",
),
(f"GRANT ALL PRIVILEGES ON {grant_scope(name)} TO {grantee}",),
}
if set(cursor.fetchall()) != expected_grants:
@@ -140,7 +154,8 @@ def check_database(driver, cursor, database, socket, record_path):
pass
except driver.Error:
raise ValueError(
"The stored application credentials cannot open the managed database."
"The stored application credentials cannot open the managed "
"database."
) from None
return "configured"
@@ -156,21 +171,26 @@ def install_database(cursor, database, socket, record_path):
password_hash = native_password_hash(record["password"])
ready = check_completion_marker(ready_path, record)
check_resources(schema, users, comment, password_hash, require_complete=ready)
check_resources(
schema, users, comment, password_hash, require_complete=ready
)
if schema is None:
cursor.execute(
f"CREATE DATABASE `{name}` CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci COMMENT %s",
f"CREATE DATABASE `{name}` CHARACTER SET utf8mb4 "
"COLLATE utf8mb4_unicode_ci COMMENT %s",
(comment,),
)
if not users:
cursor.execute(
"CREATE USER %s@'localhost' IDENTIFIED VIA mysql_native_password USING %s",
"CREATE USER %s@'localhost' IDENTIFIED VIA mysql_native_password "
"USING %s",
(name, password_hash),
)
cursor.execute(
f"GRANT ALL PRIVILEGES ON {grant_scope(name)} TO %s@'localhost'", (name,)
f"GRANT ALL PRIVILEGES ON {grant_scope(name)} TO %s@'localhost'",
(name,),
)
if not ready:
write_new_file(ready_path, record["ownership"] + "\n", mode=0o600)
@@ -182,7 +202,8 @@ def reserve_credentials(database, socket, path, ready_path, schema, users):
if os.path.lexists(ready_path) or schema is not None or users:
raise ValueError(
"The database name or login already exists outside Coulobre's registry."
"The database name or login already exists outside Coulobre's "
"registry."
)
record = {
**credential_identity(database, socket),
@@ -206,7 +227,9 @@ def load_credentials(database, socket, path):
try:
record = json.loads(read_root_file(path, mode=0o600))
except (json.JSONDecodeError, UnicodeDecodeError):
raise ValueError("The local credentials record is unreadable.") from None
raise ValueError(
"The local credentials record is unreadable."
) from None
identity = credential_identity(database, socket)
if (
not isinstance(record, dict)
@@ -218,7 +241,8 @@ def load_credentials(database, socket, path):
or not record["ownership"]
):
raise ValueError(
"The local credentials record conflicts with the manifest or socket."
"The local credentials record conflicts with the manifest "
"or socket."
)
return record
@@ -229,29 +253,40 @@ def check_completion_marker(path, record):
try:
marker = read_root_file(path, mode=0o600).strip()
except UnicodeDecodeError:
raise ValueError("The database completion marker is unreadable.") from None
raise ValueError(
"The database completion marker is unreadable."
) from None
if marker != record["ownership"]:
raise ValueError(
"The database completion marker conflicts with its credentials record."
"The database completion marker conflicts with its credentials "
"record."
)
return True
def check_resources(schema, users, comment, password_hash, *, require_complete):
def check_resources(
schema, users, comment, password_hash, *, require_complete
):
if require_complete and (schema is None or not users):
raise ValueError(
"The managed database or login is missing. Restore it before reapplying."
"The managed database or login is missing. "
"Restore it before reapplying."
)
if schema is not None and schema != (comment,):
raise ValueError("The existing database has a different ownership marker.")
if users and users != (("localhost", "mysql_native_password", password_hash),):
raise ValueError(
"The existing database has a different ownership marker."
)
if users and users != (
("localhost", "mysql_native_password", password_hash),
):
raise ValueError(
"The existing MariaDB login differs from its managed credentials."
)
def grant_scope(name):
# A database-level GRANT treats underscores as wildcards, even in backticks.
# A database-level GRANT treats underscores as wildcards, even in
# backticks.
escaped_name = name.replace("_", r"\_")
return f"`{escaped_name}`.*"
+37 -12
View File
@@ -81,11 +81,15 @@ class BackupInventory:
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():
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):
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
@@ -100,7 +104,12 @@ class BackupInventory:
tail and tail != [".direct_imap_backup"]
):
self.domain(domain).mail_files += 1
case ("domains", domain, "public_html" | "private_html", *tail) if tail:
case (
"domains",
domain,
"public_html" | "private_html",
*tail,
) if tail:
self.domain(domain).website_files += 1
case ("domains", domain, "domain.conf"):
self.domain(domain)
@@ -161,7 +170,9 @@ def read_account_settings(text):
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.")
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):
@@ -188,7 +199,9 @@ def archive_stream(path):
stderr=subprocess.DEVNULL,
)
except FileNotFoundError:
raise ValueError("Install zstd to inspect Zstandard backups.") from None
raise ValueError(
"Install zstd to inspect Zstandard backups."
) from None
with decoder:
try:
yield decoder.stdout
@@ -196,7 +209,9 @@ def archive_stream(path):
decoder.kill()
raise
if decoder.wait():
raise ValueError("The Zstandard backup is damaged or incomplete.")
raise ValueError(
"The Zstandard backup is damaged or incomplete."
)
else:
yield source
@@ -205,7 +220,9 @@ 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.")
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.")
@@ -223,7 +240,9 @@ def open_backup(path):
try:
with (
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,
):
yield archive
except (EOFError, tarfile.TarError, zlib.error, gzip.BadGzipFile):
@@ -235,7 +254,7 @@ def open_backup(path):
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.
# Forward-only reads do not need tarfile's member cache.
archive.members.clear()
check_tar_padding(archive)
@@ -256,19 +275,25 @@ def main(argv=None):
)
inspect.add_argument("backup", type=Path)
stage = commands.add_parser(
"stage-website", help="Stage one DirectAdmin website in a new local directory."
"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")
stage.add_argument(
"--source-root", choices=DOCUMENT_ROOTS, default="public_html"
)
args = parser.parse_args(argv)
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
args.backup,
args.domain,
args.destination,
source_root=args.source_root,
)
else:
report = inspect_backup(args.backup)
+16 -5
View File
@@ -22,7 +22,9 @@ def stage_website(backup, domain, destination, *, source_root="public_html"):
destination.mkdir(mode=0o700)
document_root = destination / "document-root"
try:
with TemporaryDirectory(dir=destination, prefix=".staging-") as directory:
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)
@@ -52,7 +54,11 @@ def copy_website(backup, domain, source_root, destination, *, on_copy=None):
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:
if (
len(parts) < 3
or parts[0] != "domains"
or parts[2] != source_root
):
continue
name = parts[1]
if name not in matches:
@@ -61,7 +67,8 @@ def copy_website(backup, domain, source_root, destination, *, on_copy=None):
continue
if source_name is not None and name != source_name:
raise ValueError(
"The backup contains multiple source directories for this domain."
"The backup contains multiple source directories for "
"this domain."
)
source_name = name
@@ -71,7 +78,9 @@ def copy_website(backup, domain, source_root, destination, *, on_copy=None):
found_root = True
elif member.isreg():
if len(parts) == 3:
raise ValueError("The selected website document root is a file.")
raise ValueError(
"The selected website document root is a file."
)
copy_member(archive, member, target)
found_root = True
files += 1
@@ -83,7 +92,9 @@ def copy_website(backup, domain, source_root, destination, *, on_copy=None):
on_copy(member, target)
if account.username is None:
raise ValueError("Expected a DirectAdmin account backup with backup/user.conf.")
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."
+38 -12
View File
@@ -65,7 +65,9 @@ def txt_chunks(text):
def quote_txt_chunk(chunk):
escaped = "".join(
chr(byte) if 32 <= byte <= 126 and byte not in (34, 92) else f"\\{byte:03d}"
chr(byte)
if 32 <= byte <= 126 and byte not in (34, 92)
else f"\\{byte:03d}"
for byte in chunk
)
return f'"{escaped}"'
@@ -95,7 +97,9 @@ class AddressRecord:
@classmethod
def from_manifest(cls, data):
if not isinstance(data, dict) or data.keys() != {"name", "address"}:
raise ValueError("Expected an address record with a name and IP address.")
raise ValueError(
"Expected an address record with a name and IP address."
)
return cls(data["name"], data["address"])
@@ -144,7 +148,9 @@ class TxtRecord:
try:
chunks = txt_chunks(self.text)
except UnicodeEncodeError:
raise ValueError("The TXT record value must be valid Unicode.") from None
raise ValueError(
"The TXT record value must be valid Unicode."
) from None
if sum(len(chunk) + 1 for chunk in chunks) > 65535:
raise ValueError("The TXT record value is too long for DNS.")
@@ -155,7 +161,9 @@ class TxtRecord:
return cls(data["name"], data["text"])
def render(self):
text = " ".join(quote_txt_chunk(chunk) for chunk in txt_chunks(self.text))
text = " ".join(
quote_txt_chunk(chunk) for chunk in txt_chunks(self.text)
)
return f"{self.name}. IN TXT {text}"
@@ -178,12 +186,21 @@ class DnsZone:
def __post_init__(self):
object.__setattr__(self, "domain", dns_name(self.domain))
object.__setattr__(self, "responsible_name", dns_name(self.responsible_name))
if type(self.serial) is not int or not 0 <= self.serial <= MAX_SOA_SERIAL:
raise ValueError("The SOA serial must be an unsigned 32-bit integer.")
object.__setattr__(
self, "responsible_name", dns_name(self.responsible_name)
)
if (
type(self.serial) is not int
or not 0 <= self.serial <= MAX_SOA_SERIAL
):
raise ValueError(
"The SOA serial must be an unsigned 32-bit integer."
)
nameservers = tuple(dns_name(name) for name in self.nameservers)
if not nameservers or len(set(nameservers)) != len(nameservers):
raise ValueError("Supply at least one nameserver and list each name once.")
raise ValueError(
"Supply at least one nameserver and list each name once."
)
object.__setattr__(self, "nameservers", nameservers)
address_names = {record.name for record in self.addresses}
@@ -193,7 +210,9 @@ class DnsZone:
in_zone(name, self.domain) and name not in address_names
for name in nameservers
):
raise ValueError("Each in-zone nameserver needs an address record.")
raise ValueError(
"Each in-zone nameserver needs an address record."
)
self.check_mail_records(address_names)
def check_mail_records(self, address_names):
@@ -302,9 +321,13 @@ class DnsZone:
def main(argv=None):
parser = argparse.ArgumentParser(prog="coulobre-dns-node")
commands = parser.add_subparsers(dest="command", required=True)
render = commands.add_parser("render", help="Render a BIND9 zone from a manifest.")
render = commands.add_parser(
"render", help="Render a BIND9 zone from a manifest."
)
render.add_argument("manifest", type=Path)
apply = commands.add_parser("apply", help="Install or update a primary BIND9 zone.")
apply = commands.add_parser(
"apply", help="Install or update a primary BIND9 zone."
)
apply.add_argument("manifest", type=Path)
commands.add_parser(
"apply-request",
@@ -330,7 +353,10 @@ def main(argv=None):
from .dns_node_apply import apply_zone
apply_zone(zone)
print(f"Applied BIND9 zone {zone.domain} at SOA serial {zone.serial}.")
print(
f"Applied BIND9 zone {zone.domain} "
f"at SOA serial {zone.serial}."
)
else:
sys.stdout.write(zone.render())
except (OSError, ValueError) as error:
+38 -15
View File
@@ -18,7 +18,9 @@ def apply_zone(zone):
if os.geteuid() != 0:
raise ValueError("Run apply as root on the BIND9 node.")
require_root_directory(ZONE_DIRECTORY, create_mode=0o755)
directory = os.open(ZONE_DIRECTORY, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW)
directory = os.open(
ZONE_DIRECTORY, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW
)
try:
fcntl.flock(directory, fcntl.LOCK_EX)
install_zone(zone, ZONE_DIRECTORY / zone.domain, directory)
@@ -31,11 +33,15 @@ def install_zone(zone, path, directory):
config = f'{{ type primary; file "{path}"; allow-update {{ "none"; }}; }};'
registered = check_registration(domain, config)
wanted = zone_file(zone)
previous = read_root_file(path, mode=0o644) if os.path.lexists(path) else None
previous = (
read_root_file(path, mode=0o644) if os.path.lexists(path) else None
)
loaded = None
if registered:
if previous is None:
raise ValueError("The registered zone is missing its managed zone file.")
raise ValueError(
"The registered zone is missing its managed zone file."
)
loaded = active_serial(domain)
if previous is not None:
@@ -45,13 +51,18 @@ def install_zone(zone, path, directory):
and loaded != saved
and not serial_is_newer(saved, loaded)
):
raise ValueError("The loaded SOA serial is ahead of the managed zone file.")
raise ValueError(
"The loaded SOA serial is ahead of the managed zone file."
)
if wanted != previous and (
not serial_is_newer(zone.serial, saved)
or (loaded is not None and not serial_is_newer(zone.serial, loaded))
or (
loaded is not None and not serial_is_newer(zone.serial, loaded)
)
):
raise ValueError(
"The manifest needs a newer SOA serial than the managed file and loaded zone."
"The manifest needs a newer SOA serial than the managed "
"file and loaded zone."
)
if wanted != previous:
@@ -69,14 +80,16 @@ def install_zone(zone, path, directory):
def check_registration(domain, config):
missing = (
f"rndc: 'showzone' failed: not found\nno matching zone '{domain}' in any view"
"rndc: 'showzone' failed: not found\n"
f"no matching zone '{domain}' in any view"
)
shown = run(*RNDC, "showzone", domain, allow_error=missing)
if shown is None:
return False
if " ".join(shown.split()) != f'zone "{domain}" {config}':
raise ValueError(
"BIND9 already has a zone outside Coulobre's managed configuration."
"BIND9 already has a zone outside Coulobre's managed "
"configuration."
)
return True
@@ -84,7 +97,7 @@ def check_registration(domain, config):
def zone_file(zone):
content = zone.render()
header = f"; Coulobre zone {zone.domain} {zone.serial}"
digest = hashlib.sha256(f"{header}\n{content}".encode("utf-8")).hexdigest()
digest = hashlib.sha256(f"{header}\n{content}".encode()).hexdigest()
return f"{header} {digest}\n{content}"
@@ -94,14 +107,21 @@ def file_serial(domain, zone_text):
matched = re.fullmatch(
rf"; Coulobre zone {re.escape(domain)} ([0-9]{{1,10}})", metadata
)
digest = hashlib.sha256(f"{metadata}\n{content}".encode("utf-8")).hexdigest()
if matched is None or checksum != digest or int(matched[1]) > MAX_SOA_SERIAL:
raise ValueError("The existing zone file is unmanaged or has been modified.")
digest = hashlib.sha256(f"{metadata}\n{content}".encode()).hexdigest()
if (
matched is None
or checksum != digest
or int(matched[1]) > MAX_SOA_SERIAL
):
raise ValueError(
"The existing zone file is unmanaged or has been modified."
)
return int(matched[1])
def serial_is_newer(candidate, previous):
# RFC 1982 compares serials over the forward half of the 32-bit range.
# RFC 1982 compares serials over the forward half of the 32-bit
# range.
distance = (candidate - previous) % (MAX_SOA_SERIAL + 1)
return 0 < distance < 2**31
@@ -128,7 +148,8 @@ def wait_for_serial(domain, serial):
return
time.sleep(0.25)
raise ValueError(
f"BIND9 has not loaded SOA serial {serial}. Reapply the manifest to retry."
f"BIND9 has not loaded SOA serial {serial}. "
"Reapply the manifest to retry."
)
@@ -147,5 +168,7 @@ def run(*command, allow_error=None):
details = result.stderr.strip() or result.stdout.strip()
if details == allow_error:
return None
raise ValueError(f"{command[0]} failed ({result.returncode}). {details}")
raise ValueError(
f"{command[0]} failed ({result.returncode}). {details}"
)
return result.stdout.strip()
+3 -1
View File
@@ -8,7 +8,9 @@ validate_domain = DomainNameValidator(accept_idna=False)
def canonical_domain(value):
try:
domain = (
idna.encode(value.strip(), uts46=True).decode("ascii").removesuffix(".")
idna.encode(value.strip(), uts46=True)
.decode("ascii")
.removesuffix(".")
)
validate_domain(domain)
except (idna.IDNAError, ValidationError) as error:
+14 -5
View File
@@ -15,7 +15,10 @@ def reseller_for_user(user):
def is_tenant(user):
return customer_for_user(user) is not None or reseller_for_user(user) is not None
return (
customer_for_user(user) is not None
or reseller_for_user(user) is not None
)
def panel_access(request):
@@ -25,7 +28,8 @@ def panel_access(request):
"is_customer": customer,
"is_reseller": reseller,
"is_tenant": customer or reseller,
"is_operator": request.user.is_authenticated and not (customer or reseller),
"is_operator": request.user.is_authenticated
and not (customer or reseller),
}
@@ -44,7 +48,8 @@ class TenantScopeMixin:
if customer_for_user(self.request.user) is not None:
return self.customer_relation is not None
return (
reseller_for_user(self.request.user) is not None or super().has_permission()
reseller_for_user(self.request.user) is not None
or super().has_permission()
)
def get_queryset(self):
@@ -53,8 +58,12 @@ class TenantScopeMixin:
if customer is not None:
if self.customer_relation is None:
return queryset.none()
return queryset.filter(**{f"{self.customer_relation}_id": customer.pk})
return queryset.filter(
**{f"{self.customer_relation}_id": customer.pk}
)
reseller = reseller_for_user(self.request.user)
if reseller is not None:
return queryset.filter(**{f"{self.reseller_relation}_id": reseller.pk})
return queryset.filter(
**{f"{self.reseller_relation}_id": reseller.pk}
)
return queryset
+13 -2
View File
@@ -1,7 +1,13 @@
from django.contrib import admin
from django.utils.html import format_html
from .models import Customer, HostingAccount, HostingPlan, Reseller, WebProvisioningPlan
from .models import (
Customer,
HostingAccount,
HostingPlan,
Reseller,
WebProvisioningPlan,
)
@admin.register(HostingAccount)
@@ -71,7 +77,12 @@ class CustomerAdmin(admin.ModelAdmin):
@admin.register(WebProvisioningPlan)
class WebProvisioningPlanAdmin(admin.ModelAdmin):
list_display = ("primary_domain", "account", "requested_at", "completed_at")
list_display = (
"primary_domain",
"account",
"requested_at",
"completed_at",
)
list_select_related = ("account",)
ordering = ("-requested_at",)
fields = (
+50 -18
View File
@@ -24,13 +24,17 @@ def plan_directadmin_import(inventory, primary_domain=None):
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.")
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"])
databases, review = plan_database_requests(
username, inventory["databases"]
)
review.extend(review_backup_data(inventory, primary_domain))
account = None
conflicts = []
@@ -49,7 +53,9 @@ def plan_directadmin_import(inventory, primary_domain=None):
"source_domains": list(domains),
"account": account,
"database_requests": databases,
"mailbox_requests": domains.get(primary_domain, {}).get("mailboxes", []),
"mailbox_requests": domains.get(primary_domain, {}).get(
"mailboxes", []
),
"conflicts": conflicts,
"problems": problems,
"manual_review": review,
@@ -63,7 +69,9 @@ def plan_database_requests(username, sources):
for source in sources:
normalized = source.lower()
suffix = normalized.removeprefix(prefix)
if normalized == suffix or not re.fullmatch(DATABASE_SUFFIX_PATTERN, suffix):
if normalized == suffix or not re.fullmatch(
DATABASE_SUFFIX_PATTERN, suffix
):
review.append(
{
"kind": "database_name",
@@ -103,12 +111,20 @@ def review_backup_data(inventory, primary_domain):
)
if domain["dns_zone"]:
entries.append({"kind": "dns_zone", "domain": name})
for field in ("website_files", "mail_files", "unrecognized_mailbox_entries"):
for field in (
"website_files",
"mail_files",
"unrecognized_mailbox_entries",
):
if domain[field]:
entries.append({"kind": field, "domain": name, "count": domain[field]})
entries.append(
{"kind": field, "domain": name, "count": domain[field]}
)
if inventory["databases"]:
entries.append({"kind": "database_dumps", "names": 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"]:
@@ -135,7 +151,9 @@ def domain_conflicts(domain):
.first()
)
if owner is not None:
conflicts.append({"kind": kind, "domain": domain, "account_id": owner})
conflicts.append(
{"kind": kind, "domain": domain, "account_id": owner}
)
return conflicts
@@ -173,14 +191,19 @@ def import_directadmin_account(inventory, primary_domain=None):
)
HostingMailbox.objects.bulk_create(
HostingMailbox(
mail_domain=mail_domain, local_part=address.split("@", 1)[0]
mail_domain=mail_domain,
local_part=address.split("@", 1)[0],
)
for address in plan["mailbox_requests"]
)
DirectAdminImport.objects.create(account=account, fingerprint=fingerprint)
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))
# Another process may have claimed the domain during the read.
refreshed = import_report(
plan_directadmin_import(inventory, primary_domain)
)
previous = previous_import(refreshed, fingerprint)
if previous is not None:
return previous
@@ -197,7 +220,8 @@ def import_report(plan):
def import_fingerprint(plan):
identity = {
key: plan[key] for key in ("account", "database_requests", "mailbox_requests")
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()
@@ -223,12 +247,18 @@ def previous_import(plan, fingerprint):
if account.primary_domain != domain:
return plan | {
"state": "blocked",
"problems": ["The imported account now uses a different primary domain."],
"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 = {
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(
@@ -239,7 +269,8 @@ def previous_import(plan, fingerprint):
return plan | {
"state": "blocked",
"problems": [
"The imported account is missing one or more original requests."
"The imported account is missing one or more original "
"requests."
],
}
return completed_import(plan, account, "already_imported")
@@ -254,7 +285,8 @@ def completed_import(plan, account, state):
"primary_domain": account.primary_domain,
},
"database_requests": [
request | {"database": DatabaseSpec(account.pk, request["suffix"]).name}
request
| {"database": DatabaseSpec(account.pk, request["suffix"]).name}
for request in plan["database_requests"]
],
"conflicts": [],
+28 -8
View File
@@ -36,20 +36,30 @@ class DnsZoneForm(forms.Form):
addresses = forms.CharField(
required=False,
widget=forms.Textarea(attrs={"rows": 5, "spellcheck": "false"}),
help_text="Enter a fully qualified name and an IPv4 or IPv6 address on each line.",
help_text=(
"Enter a fully qualified name and an IPv4 or IPv6 address "
"on each line."
),
)
mx_records = forms.CharField(
label="MX records",
required=False,
widget=forms.Textarea(attrs={"rows": 3, "spellcheck": "false"}),
help_text="Enter a name, priority and mail server on each line, such as @ 10 mx.example.net.",
help_text=(
"Enter a name, priority and mail server on each line, "
"such as @ 10 mx.example.net."
),
)
txt_records = forms.CharField(
label="TXT records",
required=False,
strip=False,
widget=forms.Textarea(attrs={"rows": 5, "spellcheck": "false"}),
help_text="Enter a name and text on each line. Use @ for the zone domain or a fully qualified name. Use a quoted JSON string to preserve special whitespace or enter an empty value.",
help_text=(
"Enter a name and text on each line. Use @ for the zone domain "
"or a fully qualified name. Use a quoted JSON string to preserve "
"special whitespace or enter an empty value."
),
)
def __init__(self, *args, domain, **kwargs):
@@ -58,7 +68,9 @@ class DnsZoneForm(forms.Form):
def clean_addresses(self):
records = []
for number, line in enumerate(self.cleaned_data["addresses"].splitlines(), 1):
for number, line in enumerate(
self.cleaned_data["addresses"].splitlines(), 1
):
if not line.strip():
continue
parts = line.split()
@@ -69,7 +81,9 @@ class DnsZoneForm(forms.Form):
try:
records.append(AddressRecord(*parts))
except ValueError as error:
raise forms.ValidationError(f"Line {number}. {error}") from error
raise forms.ValidationError(
f"Line {number}. {error}"
) from error
return tuple(records)
def clean_mx_records(self):
@@ -80,13 +94,17 @@ class DnsZoneForm(forms.Form):
def clean_mail_records(self, field, parse):
records = []
for number, line in enumerate(self.cleaned_data[field].splitlines(), 1):
for number, line in enumerate(
self.cleaned_data[field].splitlines(), 1
):
if not line.strip():
continue
try:
records.append(parse(line))
except ValueError as error:
raise forms.ValidationError(f"Line {number}. {error}") from error
raise forms.ValidationError(
f"Line {number}. {error}"
) from error
return tuple(records)
def parse_mx_record(self, line):
@@ -97,7 +115,9 @@ class DnsZoneForm(forms.Form):
raise ValueError(
"Enter a name, an integer priority and a mail server."
) from None
return MxRecord(self.domain if name == "@" else name, priority, exchange)
return MxRecord(
self.domain if name == "@" else name, priority, exchange
)
def parse_txt_record(self, line):
try:
+7 -3
View File
@@ -16,17 +16,21 @@ def queue_dns_publication(zone_id, expected_serial):
zone = zones.select_for_update().get()
if str(zone.serial) != expected_serial:
raise ValueError(
"This zone changed before publication. Reload the account and try again."
"This zone changed before publication. "
"Reload the account and try again."
)
manifest = zone.spec.manifest()
if len(encode_manifest(manifest)) > DNS_REQUEST_LIMIT:
raise ValueError("Local DNS publishing accepts zone manifests up to 1 MiB.")
raise ValueError(
"Local DNS publishing accepts zone manifests up to 1 MiB."
)
jobs = DnsPublication.objects
snapshot = {"manifest": manifest, "serial": zone.serial}
job, created = jobs.get_or_create(zone=zone, defaults=snapshot)
if not created:
jobs.requeue(
jobs.filter(pk=job.pk).exclude(serial=zone.serial, problem=""), **snapshot
jobs.filter(pk=job.pk).exclude(serial=zone.serial, problem=""),
**snapshot,
)
return zone
+3 -1
View File
@@ -15,4 +15,6 @@ class DomainNameField(models.CharField):
try:
return canonical_domain(value)
except ValueError as error:
raise ValidationError(validate_domain.message, code="invalid") from error
raise ValidationError(
validate_domain.message, code="invalid"
) from error
@@ -10,7 +10,8 @@ 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."
"Create a hosting account and its supported requests "
"from a DirectAdmin backup."
)
def add_arguments(self, parser):
@@ -22,11 +23,15 @@ class Command(BaseCommand):
def handle(self, *args, **options):
try:
inventory = inspect_backup(options["backup"])
result = import_directadmin_account(inventory, options["primary_domain"])
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
raise CommandError(
"The panel database rejected the import."
) from None
self.stdout.write(json.dumps(result, indent=2))
if result["state"] == "blocked":
raise CommandError(
@@ -8,7 +8,10 @@ from coulobre.hosting.directadmin_import import plan_directadmin_import
class Command(BaseCommand):
help = "Preview a DirectAdmin account import against the current panel database."
help = (
"Preview a DirectAdmin account import against the current "
"panel database."
)
def add_arguments(self, parser):
parser.add_argument("backup", type=Path)
@@ -19,7 +22,9 @@ class Command(BaseCommand):
def handle(self, *args, **options):
try:
inventory = inspect_backup(options["backup"])
plan = plan_directadmin_import(inventory, options["primary_domain"])
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))
@@ -29,7 +29,10 @@ class Migration(migrations.Migration):
coulobre.hosting.fields.DomainNameField(max_length=253),
),
("requested_at", models.DateTimeField(auto_now_add=True)),
("last_dispatched_at", models.DateTimeField(blank=True, null=True)),
(
"last_dispatched_at",
models.DateTimeField(blank=True, null=True),
),
("completed_at", models.DateTimeField(blank=True, null=True)),
("apache_config", models.TextField(blank=True)),
(
@@ -26,12 +26,16 @@ class Migration(migrations.Migration):
(
"suffix",
models.CharField(
help_text="Use 1 to 24 lowercase letters, digits, or underscores. Start with a letter.",
help_text=(
"Use 1 to 24 lowercase letters, digits, or "
"underscores. Start with a letter."
),
max_length=24,
validators=[
django.core.validators.RegexValidator(
"\\A[a-z][a-z0-9_]{0,23}\\Z",
"Use 1 to 24 lowercase letters, digits, or underscores. Start with a letter.",
"Use 1 to 24 lowercase letters, digits, or "
"underscores. Start with a letter.",
)
],
verbose_name="database suffix",
@@ -14,7 +14,10 @@ class Migration(migrations.Migration):
name="database_limit",
field=models.PositiveIntegerField(
blank=True,
help_text="Leave blank for unlimited. Enter 0 to block new database requests.",
help_text=(
"Leave blank for unlimited. "
"Enter 0 to block new database requests."
),
null=True,
),
),
@@ -23,7 +26,10 @@ class Migration(migrations.Migration):
name="mailbox_limit",
field=models.PositiveIntegerField(
blank=True,
help_text="Leave blank for unlimited. Enter 0 to block new mailbox requests.",
help_text=(
"Leave blank for unlimited. "
"Enter 0 to block new mailbox requests."
),
null=True,
),
),
@@ -27,7 +27,10 @@ class Migration(migrations.Migration):
"requested_at",
models.DateTimeField(default=django.utils.timezone.now),
),
("last_dispatched_at", models.DateTimeField(blank=True, null=True)),
(
"last_dispatched_at",
models.DateTimeField(blank=True, null=True),
),
("started_at", models.DateTimeField(blank=True, null=True)),
("finished_at", models.DateTimeField(blank=True, null=True)),
("problem", models.TextField(blank=True)),
@@ -27,7 +27,10 @@ class Migration(migrations.Migration):
"requested_at",
models.DateTimeField(default=django.utils.timezone.now),
),
("last_dispatched_at", models.DateTimeField(blank=True, null=True)),
(
"last_dispatched_at",
models.DateTimeField(blank=True, null=True),
),
("started_at", models.DateTimeField(blank=True, null=True)),
("finished_at", models.DateTimeField(blank=True, null=True)),
("problem", models.TextField(blank=True)),
@@ -27,7 +27,10 @@ class Migration(migrations.Migration):
"requested_at",
models.DateTimeField(default=django.utils.timezone.now),
),
("last_dispatched_at", models.DateTimeField(blank=True, null=True)),
(
"last_dispatched_at",
models.DateTimeField(blank=True, null=True),
),
("started_at", models.DateTimeField(blank=True, null=True)),
("finished_at", models.DateTimeField(blank=True, null=True)),
("problem", models.TextField(blank=True)),
@@ -27,7 +27,10 @@ class Migration(migrations.Migration):
"requested_at",
models.DateTimeField(default=django.utils.timezone.now),
),
("last_dispatched_at", models.DateTimeField(blank=True, null=True)),
(
"last_dispatched_at",
models.DateTimeField(blank=True, null=True),
),
("started_at", models.DateTimeField(blank=True, null=True)),
("finished_at", models.DateTimeField(blank=True, null=True)),
("problem", models.TextField(blank=True)),
+43 -25
View File
@@ -4,7 +4,11 @@ from django.db import models
from django.urls import reverse
from django.utils import timezone
from coulobre.database_node import DATABASE_SUFFIX_PATTERN, INVALID_SUFFIX, DatabaseSpec
from coulobre.database_node import (
DATABASE_SUFFIX_PATTERN,
INVALID_SUFFIX,
DatabaseSpec,
)
from coulobre.dns_node import (
MAX_SOA_SERIAL,
AddressRecord,
@@ -22,17 +26,20 @@ class Reseller(models.Model):
settings.AUTH_USER_MODEL,
on_delete=models.PROTECT,
related_name="hosting_reseller",
limit_choices_to={"is_superuser": False, "hosting_customer__isnull": True},
limit_choices_to={
"is_superuser": False,
"hosting_customer__isnull": True,
},
)
account_limit = models.PositiveIntegerField(default=0)
hosting_plans = models.ManyToManyField("HostingPlan", blank=True)
def may_create_accounts(self):
return self.account_limit > 0 and self.hosting_plans.exists()
def __str__(self):
return self.user.get_username()
def may_create_accounts(self):
return self.account_limit > 0 and self.hosting_plans.exists()
class Customer(models.Model):
user = models.OneToOneField(
@@ -56,12 +63,17 @@ class HostingPlan(models.Model):
database_limit = models.PositiveIntegerField(
blank=True,
null=True,
help_text="Leave blank for unlimited. Enter 0 to block new database requests.",
help_text=(
"Leave blank for unlimited. "
"Enter 0 to block new database requests."
),
)
mailbox_limit = models.PositiveIntegerField(
blank=True,
null=True,
help_text="Leave blank for unlimited. Enter 0 to block new mailbox requests.",
help_text=(
"Leave blank for unlimited. Enter 0 to block new mailbox requests."
),
)
class Meta:
@@ -85,12 +97,12 @@ class HostingAccount(models.Model):
)
created_at = models.DateTimeField(auto_now_add=True)
def get_absolute_url(self):
return reverse("panel:account", kwargs={"pk": self.pk})
def __str__(self):
return str(self.primary_domain)
def get_absolute_url(self):
return reverse("panel:account", kwargs={"pk": self.pk})
class HostingDatabase(models.Model):
account = models.ForeignKey(
@@ -112,17 +124,19 @@ class HostingDatabase(models.Model):
)
]
def __str__(self):
return self.spec.name
@property
def spec(self):
return DatabaseSpec(self.account_id, self.suffix)
def __str__(self):
return self.spec.name
class DirectAdminImport(models.Model):
account = models.OneToOneField(
HostingAccount, on_delete=models.CASCADE, related_name="directadmin_import"
HostingAccount,
on_delete=models.CASCADE,
related_name="directadmin_import",
)
fingerprint = models.CharField(max_length=64, unique=True)
@@ -148,6 +162,9 @@ class HostingDnsZone(models.Model):
)
]
def __str__(self):
return str(self.domain)
@property
def spec(self):
return DnsZone(
@@ -158,15 +175,14 @@ class HostingDnsZone(models.Model):
addresses=tuple(
AddressRecord.from_manifest(item) for item in self.addresses
),
mx_records=tuple(MxRecord.from_manifest(item) for item in self.mx_records),
mx_records=tuple(
MxRecord.from_manifest(item) for item in self.mx_records
),
txt_records=tuple(
TxtRecord.from_manifest(item) for item in self.txt_records
),
)
def __str__(self):
return str(self.domain)
class HostingMailDomain(models.Model):
account = models.ForeignKey(
@@ -193,13 +209,13 @@ class HostingMailbox(models.Model):
)
]
def __str__(self):
return self.spec.address
@property
def spec(self):
return MailboxSpec(self.mail_domain.domain, self.local_part)
def __str__(self):
return self.spec.address
class WebProvisioningPlan(models.Model):
account = models.ForeignKey(HostingAccount, on_delete=models.CASCADE)
@@ -209,6 +225,9 @@ class WebProvisioningPlan(models.Model):
completed_at = models.DateTimeField(null=True, blank=True)
apache_config = models.TextField(blank=True)
def __str__(self):
return str(self.primary_domain)
@classmethod
def for_account(cls, account):
return cls(account=account, primary_domain=account.primary_domain)
@@ -221,9 +240,6 @@ class WebProvisioningPlan(models.Model):
and self.primary_domain == self.account.primary_domain
)
def __str__(self):
return str(self.primary_domain)
class ProvisioningJobManager(models.Manager):
def queue(self, **target):
@@ -262,7 +278,9 @@ class ProvisioningJob(models.Model):
class WebActivation(ProvisioningJob):
plan = models.OneToOneField(
WebProvisioningPlan, on_delete=models.CASCADE, related_name="activation"
WebProvisioningPlan,
on_delete=models.CASCADE,
related_name="activation",
)
+10 -3
View File
@@ -5,12 +5,17 @@ RESPONSE_LIMIT = 32768
def activate_local_site(site):
apply_on_local_node(site, "/run/coulobre-web-apply.sock", "web node", "site")
apply_on_local_node(
site, "/run/coulobre-web-apply.sock", "web node", "site"
)
def provision_local_database(database):
apply_on_local_node(
database, "/run/coulobre-database-apply.sock", "MariaDB node", "database"
database,
"/run/coulobre-database-apply.sock",
"MariaDB node",
"database",
)
@@ -47,7 +52,9 @@ def apply_on_local_node(spec, socket_path, node, resource, *, identity=None):
if len(body) > RESPONSE_LIMIT:
raise ValueError(f"The {node} returned an oversized response.")
invalid_response = f"The {node} returned an invalid response for this {resource}."
invalid_response = (
f"The {node} returned an invalid response for this {resource}."
)
try:
reply = json.loads(body.decode("utf-8"))
state, problem = reply["state"], reply["problem"]
+9 -3
View File
@@ -9,18 +9,24 @@ from .models import Reseller
def create_reseller_account(access, account):
candidates = Reseller.objects.filter(pk=access.pk, user_id=access.user_id)
if connection.vendor == "sqlite":
# SQLite needs a write before the quota read to serialize writers.
# Write first so SQLite locks writers before the quota check.
candidates.update(account_limit=F("account_limit"))
reseller = candidates.select_for_update().first()
if reseller is None:
raise ValidationError({NON_FIELD_ERRORS: "Your reseller access has changed."})
raise ValidationError(
{NON_FIELD_ERRORS: "Your reseller access has changed."}
)
if reseller.hostingaccount_set.count() >= reseller.account_limit:
raise ValidationError(
{NON_FIELD_ERRORS: "Your hosting account limit has been reached."}
)
if not reseller.hosting_plans.filter(pk=account.hosting_plan_id).exists():
raise ValidationError(
{"hosting_plan": "This hosting plan is no longer available to you."}
{
"hosting_plan": (
"This hosting plan is no longer available to you."
)
}
)
account.reseller = reseller
+10 -4
View File
@@ -12,7 +12,7 @@ def lock_hosting_account(account_id, customer_id):
if customer_id is not None:
accounts = accounts.filter(customer_id=customer_id)
if connection.vendor == "sqlite":
# Acquire the write lock before reading the account and resource counts.
# Lock writes before reading the account and resource counts.
accounts.update(hosting_plan=F("hosting_plan"))
return accounts.select_for_update().get()
@@ -32,7 +32,9 @@ def create_database_request(account_id, suffix, *, customer_id=None):
and plan.database_limit is not None
and databases.count() >= plan.database_limit
):
raise ValidationError("This hosting account has reached its database limit.")
raise ValidationError(
"This hosting account has reached its database limit."
)
return databases.create(suffix=suffix)
@@ -48,7 +50,9 @@ def create_mailbox_request(account_id, local_part, *, customer_id=None):
domain=spec.domain, defaults={"account": account}
)
if mail_domain.account_id != account.pk:
raise ValidationError("This mail domain belongs to another hosting account.")
raise ValidationError(
"This mail domain belongs to another hosting account."
)
if mail_domain.mailboxes.filter(local_part=spec.local_part).exists():
raise ValidationError(
{"local_part": "This mailbox has already been requested."}
@@ -58,5 +62,7 @@ def create_mailbox_request(account_id, local_part, *, customer_id=None):
if plan and plan.mailbox_limit is not None:
mailboxes = HostingMailbox.objects.filter(mail_domain__account=account)
if mailboxes.count() >= plan.mailbox_limit:
raise ValidationError("This hosting account has reached its mailbox limit.")
raise ValidationError(
"This hosting account has reached its mailbox limit."
)
return mail_domain.mailboxes.create(local_part=spec.local_part)
+25 -11
View File
@@ -35,7 +35,8 @@ def dispatch_web_plans():
pending_ids = (
WebProvisioningPlan.objects.filter(completed_at__isnull=True)
.filter(
Q(last_dispatched_at__isnull=True) | Q(last_dispatched_at__lte=stale_before)
Q(last_dispatched_at__isnull=True)
| Q(last_dispatched_at__lte=stale_before)
)
.order_by("requested_at", "pk")
.values_list("pk", flat=True)[:100]
@@ -50,12 +51,16 @@ def dispatch_web_plans():
@shared_task(acks_late=True, reject_on_worker_lost=True)
def render_web_plan(plan_id):
pending = WebProvisioningPlan.objects.filter(pk=plan_id, completed_at__isnull=True)
pending = WebProvisioningPlan.objects.filter(
pk=plan_id, completed_at__isnull=True
)
plan = pending.first()
if plan is None:
return
apache_config = WebSite(plan.account_id, plan.primary_domain).render("apache")
apache_config = WebSite(plan.account_id, plan.primary_domain).render(
"apache"
)
pending.update(apache_config=apache_config, completed_at=timezone.now())
@@ -71,7 +76,9 @@ def dispatch_web_activations():
def dispatch_database_provisioning():
if settings.LOCAL_DATABASE_PROVISIONING:
dispatch_provisioning_jobs(
DatabaseProvisioning, provision_database, DATABASE_PROVISIONING_QUEUE
DatabaseProvisioning,
provision_database,
DATABASE_PROVISIONING_QUEUE,
)
@@ -96,7 +103,8 @@ def dispatch_provisioning_jobs(model, task, queue):
waiting = model.objects.filter(finished_at__isnull=True)
pending = (
waiting.filter(
Q(last_dispatched_at__isnull=True) | Q(last_dispatched_at__lte=stale_before)
Q(last_dispatched_at__isnull=True)
| Q(last_dispatched_at__lte=stale_before)
)
.filter(Q(started_at__isnull=True) | Q(started_at__lte=stale_before))
.order_by("requested_at", "pk")
@@ -116,7 +124,8 @@ def activate_web_plan(activation_id):
WebActivation.objects.select_related("plan__account"),
activation_id,
apply_web_activation,
"Could not complete the request to the local web node. Check its socket and try again.",
"Could not complete the request to the local web node. "
"Check its socket and try again.",
)
@@ -124,7 +133,8 @@ def apply_web_activation(activation):
plan = activation.plan
if not plan.can_export:
raise ValueError(
"Request a completed Apache preview for the current account domain."
"Request a completed Apache preview for the current "
"account domain."
)
activate_local_site(WebSite(plan.account_id, plan.primary_domain))
@@ -136,7 +146,8 @@ def provision_database(provisioning_id):
DatabaseProvisioning.objects.select_related("database"),
provisioning_id,
apply_database_provisioning,
"Could not complete the request to the local MariaDB node. Check its socket and try again.",
"Could not complete the request to the local MariaDB node. "
"Check its socket and try again.",
)
@@ -151,7 +162,8 @@ def publish_dns_zone(publication_id):
DnsPublication.objects.all(),
publication_id,
apply_dns_publication,
"Could not complete the request to the local BIND9 node. Check its socket and try again.",
"Could not complete the request to the local BIND9 node. "
"Check its socket and try again.",
)
@@ -168,7 +180,8 @@ def provision_mailbox(provisioning_id):
MailboxProvisioning.objects.select_related("mailbox__mail_domain"),
provisioning_id,
apply_mailbox_provisioning,
"Could not complete the request to the local mail node. Check its socket and try again.",
"Could not complete the request to the local mail node. "
"Check its socket and try again.",
)
@@ -180,7 +193,8 @@ def run_provisioning_job(jobs, job_id, apply, connection_problem):
started_at = timezone.now()
pending = jobs.filter(pk=job_id, finished_at__isnull=True)
claim = pending.filter(
Q(started_at__isnull=True) | Q(started_at__lte=started_at - REDISPATCH_AFTER)
Q(started_at__isnull=True)
| Q(started_at__lte=started_at - REDISPATCH_AFTER)
)
if not claim.update(started_at=started_at):
return
+98 -34
View File
@@ -25,7 +25,9 @@ class CustomerAccessTests(TestCase):
def setUpTestData(cls):
users = get_user_model().objects
cls.operator = users.create_superuser("operator")
cls.alice = users.create_user("alice", password="test-customer-password")
cls.alice = users.create_user(
"alice", password="test-customer-password"
)
cls.bob = users.create_user("bob")
cls.customer = Customer.objects.create(user=cls.alice)
cls.other_customer = Customer.objects.create(user=cls.bob)
@@ -45,7 +47,9 @@ class CustomerAccessTests(TestCase):
name="Unassigned website",
primary_domain="unassigned.example",
)
cls.database = HostingDatabase.objects.create(account=cls.account, suffix="cms")
cls.database = HostingDatabase.objects.create(
account=cls.account, suffix="cms"
)
cls.zone = HostingDnsZone.objects.create(
account=cls.account,
domain="alice.example",
@@ -64,7 +68,9 @@ class CustomerAccessTests(TestCase):
def test_customer_can_sign_in_and_see_only_assigned_accounts(self):
additional = HostingAccount.objects.create(
name="Alice blog", primary_domain="blog.example", customer=self.customer
name="Alice blog",
primary_domain="blog.example",
customer=self.customer,
)
self.assertRedirects(
self.client.post(
@@ -91,7 +97,8 @@ class CustomerAccessTests(TestCase):
for account in (self.other_account, self.unassigned_account):
with self.subTest(account=account):
self.assertEqual(
self.client.get(account.get_absolute_url()).status_code, 404
self.client.get(account.get_absolute_url()).status_code,
404,
)
def test_operator_permissions_do_not_widen_customer_access(self):
@@ -145,15 +152,19 @@ class CustomerAccessTests(TestCase):
):
with self.subTest(route=route):
self.assertEqual(
self.client.post(reverse(route, args=args)).status_code, 403
self.client.post(reverse(route, args=args)).status_code,
403,
)
admin_url = reverse("admin:hosting_hostingaccount_changelist")
self.assertRedirects(
self.client.get(admin_url), f"{reverse('admin:login')}?next={admin_url}"
self.client.get(admin_url),
f"{reverse('admin:login')}?next={admin_url}",
)
def test_customer_can_request_databases_and_mailboxes_up_to_the_plan_limits(self):
def test_customer_requests_respect_database_and_mailbox_plan_limits(
self,
):
HostingPlan.objects.filter(pk=self.package.pk).update(
database_limit=2, mailbox_limit=2
)
@@ -164,7 +175,9 @@ class CustomerAccessTests(TestCase):
self.assertContains(detail, "Request mailbox")
database_url = reverse("panel:database_create", args=[self.account.pk])
self.assertContains(self.client.get(database_url), "Request MariaDB database")
self.assertContains(
self.client.get(database_url), "Request MariaDB database"
)
self.assertRedirects(
self.client.post(database_url, {"suffix": "shop"}), account_url
)
@@ -184,11 +197,18 @@ class CustomerAccessTests(TestCase):
"This hosting account has reached its mailbox limit.",
)
self.assertEqual(
HostingMailbox.objects.filter(mail_domain__account=self.account).count(), 2
HostingMailbox.objects.filter(
mail_domain__account=self.account
).count(),
2,
)
self.assertContains(
self.client.get(account_url), "sales@alice.example"
)
self.assertContains(self.client.get(account_url), "sales@alice.example")
def test_customer_cannot_open_or_submit_resource_forms_for_other_accounts(self):
def test_customer_cannot_open_or_submit_resource_forms_for_other_accounts(
self,
):
self.alice.user_permissions.add(
*Permission.objects.filter(content_type__app_label="hosting")
)
@@ -201,11 +221,15 @@ class CustomerAccessTests(TestCase):
with self.subTest(account=account, route=route):
url = reverse(route, args=[account.pk])
self.assertEqual(self.client.get(url).status_code, 404)
self.assertEqual(self.client.post(url, data).status_code, 404)
self.assertEqual(
self.client.post(url, data).status_code, 404
)
self.assertEqual(HostingDatabase.objects.count(), 1)
self.assertEqual(HostingMailbox.objects.count(), 1)
def test_database_request_rechecks_customer_assignment_before_writing(self):
def test_database_request_rechecks_customer_assignment_before_writing(
self,
):
self.client.force_login(self.alice)
def reassign_before_create(account_id, **kwargs):
@@ -215,7 +239,9 @@ class CustomerAccessTests(TestCase):
return create_database_request(account_id, **kwargs)
with patch.object(
DatabaseCreate, "create_request", side_effect=reassign_before_create
DatabaseCreate,
"create_request",
side_effect=reassign_before_create,
):
response = self.client.post(
reverse("panel:database_create", args=[self.account.pk]),
@@ -228,7 +254,9 @@ class CustomerAccessTests(TestCase):
user = get_user_model().objects.create_user("charlie")
self.client.force_login(self.operator)
self.assertRedirects(
self.client.post(reverse("admin:hosting_customer_add"), {"user": user.pk}),
self.client.post(
reverse("admin:hosting_customer_add"), {"user": user.pk}
),
reverse("admin:hosting_customer_changelist"),
)
customer = Customer.objects.get(user=user)
@@ -252,7 +280,8 @@ class CustomerAccessTests(TestCase):
self.client.get(self.account.get_absolute_url()).status_code, 404
)
self.assertContains(
self.client.get(reverse("panel:accounts")), "No hosting accounts yet."
self.client.get(reverse("panel:accounts")),
"No hosting accounts yet.",
)
self.client.force_login(user)
self.assertContains(
@@ -279,10 +308,14 @@ class CustomerManagementTests(TestCase):
)
cls.customer = Customer.objects.create(user=users.create_user("alice"))
cls.account = HostingAccount.objects.create(
name="Alice hosting", primary_domain="alice.example", customer=cls.customer
name="Alice hosting",
primary_domain="alice.example",
customer=cls.customer,
)
def test_operator_can_create_customer_and_assign_hosting_in_the_panel(self):
def test_operator_can_create_customer_and_assign_hosting_in_the_panel(
self,
):
self.client.force_login(self.operator)
customers = reverse("panel:customers")
self.assertContains(self.client.get(customers), "Add customer")
@@ -301,7 +334,9 @@ class CustomerManagementTests(TestCase):
),
customers,
)
charlie = Customer.objects.select_related("user").get(user__username="charlie")
charlie = Customer.objects.select_related("user").get(
user__username="charlie"
)
self.assertFalse(charlie.user.is_staff)
self.assertFalse(charlie.user.is_superuser)
results = self.client.get(customers, {"q": "CHARLIE"})
@@ -322,19 +357,29 @@ class CustomerManagementTests(TestCase):
self.client.logout()
self.assertRedirects(
self.client.post(
reverse("panel:login"), {"username": "charlie", "password": password}
reverse("panel:login"),
{"username": "charlie", "password": password},
),
reverse("panel:accounts"),
)
self.assertContains(self.client.get(reverse("panel:accounts")), account.name)
self.assertContains(
self.client.get(reverse("panel:accounts")), account.name
)
def test_customer_creation_preserves_existing_users_and_validates_passwords(self):
def test_create_customer_preserves_users_and_validates_passwords(
self,
):
self.client.force_login(self.operator)
existing = get_user_model().objects.create_user("existing")
url = reverse("panel:customer_create")
password = "initial-correct-horse-battery-staple"
duplicate = self.client.post(
url, {"username": "Existing", "password1": password, "password2": password}
url,
{
"username": "Existing",
"password1": password,
"password2": password,
},
)
self.assertIn("username", duplicate.context["form"].errors)
self.assertFalse(Customer.objects.filter(user=existing).exists())
@@ -342,9 +387,13 @@ class CustomerManagementTests(TestCase):
url, {"username": "new", "password1": "123", "password2": "123"}
)
self.assertIn("password2", invalid.context["form"].errors)
self.assertFalse(get_user_model().objects.filter(username="new").exists())
self.assertFalse(
get_user_model().objects.filter(username="new").exists()
)
def test_suspend_blocks_an_existing_session_and_preserves_assignments(self):
def test_suspend_blocks_an_existing_session_and_preserves_assignments(
self,
):
self.client.force_login(self.customer.user)
self.assertContains(
self.client.get(self.account.get_absolute_url()), self.account.name
@@ -362,15 +411,19 @@ class CustomerManagementTests(TestCase):
self.assertContains(operator_client.get(customers), "Suspended")
account_url = self.account.get_absolute_url()
self.assertRedirects(
self.client.get(account_url), f"{reverse('panel:login')}?next={account_url}"
self.client.get(account_url),
f"{reverse('panel:login')}?next={account_url}",
)
self.account.refresh_from_db()
self.assertEqual(self.account.customer_id, self.customer.pk)
filtered = f"{customers}?q=alice"
self.assertContains(operator_client.get(filtered), f'action="{url}?q=alice"')
self.assertContains(
operator_client.get(filtered), f'action="{url}?q=alice"'
)
self.assertRedirects(
operator_client.post(f"{url}?q=alice", {"access": "restore"}), filtered
operator_client.post(f"{url}?q=alice", {"access": "restore"}),
filtered,
)
self.customer.user.refresh_from_db()
self.assertTrue(self.customer.user.is_active)
@@ -378,12 +431,17 @@ class CustomerManagementTests(TestCase):
self.assertContains(self.client.get(account_url), self.account.name)
def test_customer_permissions_cannot_manage_other_customers(self):
self.customer.user.user_permissions.add(*self.operator.user_permissions.all())
self.customer.user.user_permissions.add(
*self.operator.user_permissions.all()
)
self.client.force_login(self.customer.user)
self.assertNotContains(
self.client.get(reverse("panel:accounts")), reverse("panel:customers")
self.client.get(reverse("panel:accounts")),
reverse("panel:customers"),
)
self.assertEqual(
self.client.get(reverse("panel:customers")).status_code, 403
)
self.assertEqual(self.client.get(reverse("panel:customers")).status_code, 403)
self.assertEqual(
self.client.post(reverse("panel:customer_create")).status_code, 403
)
@@ -398,14 +456,18 @@ class CustomerManagementTests(TestCase):
def test_view_only_operator_and_privileged_logins_cannot_be_modified(self):
users = get_user_model().objects
reader = users.create_user("reader")
reader.user_permissions.add(Permission.objects.get(codename="view_customer"))
reader.user_permissions.add(
Permission.objects.get(codename="view_customer")
)
url = reverse("panel:customer_access", args=[self.customer.pk])
self.client.force_login(reader)
response = self.client.get(reverse("panel:customers"))
self.assertContains(response, "alice")
self.assertNotContains(response, "Add customer")
self.assertNotContains(response, "Suspend sign-in")
self.assertEqual(self.client.post(url, {"access": "suspend"}).status_code, 403)
self.assertEqual(
self.client.post(url, {"access": "suspend"}).status_code, 403
)
self.assertEqual(
self.client.get(reverse("panel:customer_create")).status_code, 403
)
@@ -413,6 +475,8 @@ class CustomerManagementTests(TestCase):
self.client.force_login(self.operator)
self.customer.user.is_staff = True
self.customer.user.save(update_fields=["is_staff"])
self.assertEqual(self.client.post(url, {"access": "suspend"}).status_code, 404)
self.assertEqual(
self.client.post(url, {"access": "suspend"}).status_code, 404
)
self.customer.user.refresh_from_db()
self.assertTrue(self.customer.user.is_active)
@@ -38,12 +38,16 @@ class DatabaseApplyRequestTests(SimpleTestCase):
code = main(["apply-request"])
return code, json.loads(output.getvalue())
def test_request_uses_the_local_socket_and_reports_only_manifest_identity(self):
def test_request_uses_the_local_socket_and_reports_only_manifest_identity(
self,
):
manifest = self.database.manifest()
code, reply = self.request(manifest)
self.apply.assert_called_once_with(self.database, DEFAULT_SOCKET)
self.assertEqual(code, 0)
self.assertEqual(reply, manifest | {"state": "configured", "problem": None})
self.assertEqual(
reply, manifest | {"state": "configured", "problem": None}
)
def test_request_rejects_a_socket_supplied_by_the_client(self):
code, reply = self.request(
@@ -67,28 +71,39 @@ class DatabaseProvisioningTests(SimpleTestCase):
self.enterContext(
patch(
"coulobre.database_node_apply.read_root_file",
side_effect=lambda path, *, mode: path.read_text(encoding="utf-8"),
side_effect=lambda path, *, mode: path.read_text(
encoding="utf-8"
),
)
)
def apply(self):
install_database(self.cursor, self.database, self.socket, self.record)
def test_creates_private_credentials_and_grants_only_the_exact_database(self):
def test_creates_private_credentials_and_grants_only_the_exact_database(
self,
):
self.apply()
credentials = json.loads(self.record.read_text())
self.assertEqual(stat.S_IMODE(self.record.stat().st_mode), 0o600)
self.assertEqual(stat.S_IMODE(self.ready.stat().st_mode), 0o600)
self.assertEqual(credentials["user"], self.database.name)
self.assertEqual(self.ready.read_text().strip(), credentials["ownership"])
self.assertEqual(
self.ready.read_text().strip(), credentials["ownership"]
)
self.cursor.execute.assert_any_call(
r"GRANT ALL PRIVILEGES ON `coulobre\_42\_site\_db`.* TO %s@'localhost'",
r"GRANT ALL PRIVILEGES ON `coulobre\_42\_site\_db`.* "
"TO %s@'localhost'",
(self.database.name,),
)
self.cursor.execute.assert_any_call(
"CREATE USER %s@'localhost' IDENTIFIED VIA mysql_native_password USING %s",
(self.database.name, native_password_hash(credentials["password"])),
"CREATE USER %s@'localhost' IDENTIFIED VIA mysql_native_password "
"USING %s",
(
self.database.name,
native_password_hash(credentials["password"]),
),
)
def test_interrupted_creation_reuses_the_reserved_password(self):
@@ -119,7 +134,9 @@ class DatabaseProvisioningTests(SimpleTestCase):
)
)
def test_existing_unmanaged_database_is_rejected_without_creating_credentials(self):
def test_unmanaged_database_is_rejected_without_creating_credentials(
self,
):
self.cursor.fetchone.return_value = ("Existing database",)
with self.assertRaisesRegex(ValueError, "outside Coulobre's registry"):
@@ -128,11 +145,15 @@ class DatabaseProvisioningTests(SimpleTestCase):
self.assertFalse(self.record.exists())
self.assertEqual(self.cursor.execute.call_count, 2)
def test_completed_deployment_with_missing_resource_requires_recovery(self):
def test_completed_deployment_with_missing_resource_requires_recovery(
self,
):
self.apply()
self.cursor.reset_mock()
with self.assertRaisesRegex(ValueError, "database or login is missing"):
with self.assertRaisesRegex(
ValueError, "database or login is missing"
):
self.apply()
self.assertEqual(self.cursor.execute.call_count, 2)
@@ -147,9 +168,13 @@ class DatabaseProvisioningTests(SimpleTestCase):
grantee = "`coulobre_42_site_db`@`localhost`"
self.grants = (
(
f"GRANT USAGE ON *.* TO {grantee} IDENTIFIED BY PASSWORD '{password_hash}'",
f"GRANT USAGE ON *.* TO {grantee} "
f"IDENTIFIED BY PASSWORD '{password_hash}'",
),
(
r"GRANT ALL PRIVILEGES ON `coulobre\_42\_site\_db`.* "
f"TO {grantee}",
),
(rf"GRANT ALL PRIVILEGES ON `coulobre\_42\_site\_db`.* TO {grantee}",),
)
self.cursor.fetchall.side_effect = [
(("localhost", "mysql_native_password", password_hash),),
@@ -163,7 +188,9 @@ class DatabaseProvisioningTests(SimpleTestCase):
driver, self.cursor, self.database, self.socket, self.record
)
def test_absent_database_has_no_local_state_or_application_connection(self):
def test_absent_database_has_no_local_state_or_application_connection(
self,
):
driver = Mock()
self.assertEqual(self.check_status(driver), "not_installed")
@@ -172,7 +199,9 @@ class DatabaseProvisioningTests(SimpleTestCase):
self.assertFalse(self.ready.exists())
driver.connect.assert_not_called()
def test_configured_database_is_opened_with_the_saved_application_login(self):
def test_configured_database_is_opened_with_the_saved_application_login(
self,
):
driver = Mock()
credentials = self.set_configured_resources()
@@ -214,6 +243,7 @@ class DatabaseProvisioningTests(SimpleTestCase):
with self.assertRaisesRegex(
ValueError,
"^The stored application credentials cannot open the managed database\\.$",
"^The stored application credentials cannot open the managed "
r"database\.$",
):
self.check_status(driver)
@@ -9,7 +9,12 @@ from django.urls import reverse
from coulobre.database_node import DatabaseSpec
from .models import Customer, DatabaseProvisioning, HostingAccount, HostingDatabase
from .models import (
Customer,
DatabaseProvisioning,
HostingAccount,
HostingDatabase,
)
from .node_client import provision_local_database
from .tasks import dispatch_database_provisioning, provision_database
@@ -35,7 +40,9 @@ class DatabaseProvisioningTests(TestCase):
cls.account = HostingAccount.objects.create(
name="Example", primary_domain="site.example", customer=customer
)
cls.database = HostingDatabase.objects.create(account=cls.account, suffix="cms")
cls.database = HostingDatabase.objects.create(
account=cls.account, suffix="cms"
)
def setUp(self):
self.client.force_login(self.operator)
@@ -91,7 +98,8 @@ class DatabaseProvisioningTests(TestCase):
self.assertRedirects(self.client.post(self.url), self.detail)
job = DatabaseProvisioning.objects.get(database=self.database)
with patch(
"coulobre.hosting.tasks.provision_local_database", side_effect=OSError
"coulobre.hosting.tasks.provision_local_database",
side_effect=OSError,
):
provision_database.run(job.pk)
detail = self.client.get(self.detail)
+52 -18
View File
@@ -16,7 +16,9 @@ class DatabaseRequestTests(TestCase):
cls.user = users.create_user("reseller")
reseller = Reseller.objects.create(user=cls.user)
cls.account = HostingAccount.objects.create(
name="Account A", primary_domain="account-a.example", reseller=reseller
name="Account A",
primary_domain="account-a.example",
reseller=reseller,
)
cls.other_account = HostingAccount.objects.create(
name="Account B", primary_domain="account-b.example"
@@ -24,7 +26,9 @@ class DatabaseRequestTests(TestCase):
def setUp(self):
self.client.force_login(self.operator)
self.request_url = reverse("panel:database_create", args=[self.account.pk])
self.request_url = reverse(
"panel:database_create", args=[self.account.pk]
)
def test_operator_can_request_a_database_and_download_its_manifest(self):
response = self.client.post(self.request_url, {"suffix": "wordpress"})
@@ -32,7 +36,9 @@ class DatabaseRequestTests(TestCase):
database = HostingDatabase.objects.get()
self.assertEqual(database.account, self.account)
name = f"coulobre_{self.account.pk}_wordpress"
self.assertContains(self.client.get(self.account.get_absolute_url()), name)
self.assertContains(
self.client.get(self.account.get_absolute_url()), name
)
manifest = self.client.get(
reverse("panel:database_manifest", args=[database.pk])
@@ -49,28 +55,37 @@ class DatabaseRequestTests(TestCase):
"suffix": "wordpress",
},
)
self.assertEqual(DatabaseSpec.from_manifest(manifest.json()).name, name)
self.assertEqual(
DatabaseSpec.from_manifest(manifest.json()).name, name
)
def test_duplicate_suffix_is_scoped_to_the_owning_account(self):
HostingDatabase.objects.create(account=self.account, suffix="wordpress")
HostingDatabase.objects.create(
account=self.account, suffix="wordpress"
)
duplicate = self.client.post(self.request_url, {"suffix": "wordpress"})
self.assertContains(
duplicate, "This account already has a database with that suffix."
)
other_url = reverse("panel:database_create", args=[self.other_account.pk])
other_url = reverse(
"panel:database_create", args=[self.other_account.pk]
)
self.assertRedirects(
self.client.post(other_url, {"suffix": "wordpress"}),
self.other_account.get_absolute_url(),
)
self.assertEqual(
len({str(database) for database in HostingDatabase.objects.all()}), 2
len({str(database) for database in HostingDatabase.objects.all()}),
2,
)
def test_request_rejects_invalid_suffixes(self):
for suffix in ("UPPER", "bad-name", "3db", "mysql`", "a" * 25):
with self.subTest(suffix=suffix):
response = self.client.post(self.request_url, {"suffix": suffix})
response = self.client.post(
self.request_url, {"suffix": suffix}
)
self.assertIn("suffix", response.context["form"].errors)
self.assertFalse(HostingDatabase.objects.exists())
@@ -86,13 +101,19 @@ class DatabaseRequestTests(TestCase):
capped, "This hosting account has reached its database limit."
)
other_url = reverse("panel:database_create", args=[self.other_account.pk])
other_url = reverse(
"panel:database_create", args=[self.other_account.pk]
)
self.assertRedirects(
self.client.post(other_url, {"suffix": "cms"}),
self.other_account.get_absolute_url(),
)
zero = HostingPlan.objects.create(name="No databases", database_limit=0)
HostingAccount.objects.filter(pk=self.account.pk).update(hosting_plan=zero)
zero = HostingPlan.objects.create(
name="No databases", database_limit=0
)
HostingAccount.objects.filter(pk=self.account.pk).update(
hosting_plan=zero
)
self.assertContains(
self.client.get(self.account.get_absolute_url()),
"1 of 0 databases requested",
@@ -102,12 +123,19 @@ class DatabaseRequestTests(TestCase):
capped, "This hosting account has reached its database limit."
)
self.assertEqual(
list(self.account.databases.values_list("suffix", flat=True)), ["cms"]
list(self.account.databases.values_list("suffix", flat=True)),
["cms"],
)
def test_reseller_view_is_scoped_and_node_actions_require_an_operator(self):
owned = HostingDatabase.objects.create(account=self.account, suffix="wordpress")
HostingDatabase.objects.create(account=self.other_account, suffix="othersite")
def test_reseller_view_is_scoped_and_node_actions_require_an_operator(
self,
):
owned = HostingDatabase.objects.create(
account=self.account, suffix="wordpress"
)
HostingDatabase.objects.create(
account=self.other_account, suffix="othersite"
)
self.client.force_login(self.user)
account = self.client.get(self.account.get_absolute_url())
self.assertContains(account, str(owned))
@@ -115,10 +143,14 @@ class DatabaseRequestTests(TestCase):
self.assertNotContains(account, "Download manifest")
self.assertNotContains(account, "Request database")
self.assertEqual(
self.client.get(self.other_account.get_absolute_url()).status_code, 404
self.client.get(self.other_account.get_absolute_url()).status_code,
404,
)
self.assertEqual(
self.client.post(self.request_url, {"suffix": "another"}).status_code, 403
self.client.post(
self.request_url, {"suffix": "another"}
).status_code,
403,
)
self.assertEqual(
self.client.get(
@@ -128,7 +160,9 @@ class DatabaseRequestTests(TestCase):
)
def test_account_deletion_protects_database_requests(self):
HostingDatabase.objects.create(account=self.account, suffix="wordpress")
HostingDatabase.objects.create(
account=self.account, suffix="wordpress"
)
with self.assertRaises(ProtectedError):
self.account.delete()
+55 -16
View File
@@ -25,7 +25,11 @@ def make_tar(entries):
member.linkname = "public_html"
archive.addfile(member)
else:
data = payload.encode("utf-8") if isinstance(payload, str) else payload
data = (
payload.encode("utf-8")
if isinstance(payload, str)
else payload
)
member.size = len(data)
archive.addfile(member, BytesIO(data))
return output.getvalue()
@@ -37,15 +41,24 @@ class DirectAdminInventoryTests(SimpleTestCase):
self.entries = [
(
"./backup/user.conf",
"username=customer\npassword=private-account-hash\ndomain=Bücher.Example\n",
"username=customer\n"
"password=private-account-hash\n"
"domain=Bücher.Example\n",
),
("backup/domains.list", "bücher.example\n"),
("backup/other.example/other.example.conf", "domain=other.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",
"Support:private-mail-hash:10\n"
"old.value+tag:other-private-hash:10\n",
),
(
"backup/xn--bcher-kva.example/xn--bcher-kva.example.db",
"; DNS zone",
),
("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"),
(
@@ -53,8 +66,14 @@ class DirectAdminInventoryTests(SimpleTestCase):
"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"),
(
"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", ""),
]
@@ -63,7 +82,9 @@ class DirectAdminInventoryTests(SimpleTestCase):
path.write_bytes(content)
return path
def test_inventory_describes_contents_without_emitting_private_payloads(self):
def test_inventory_describes_contents_without_emitting_private_payloads(
self,
):
path = self.save(
gzip.compress(make_tar(self.entries)), "user.admin.customer.tar.gz"
)
@@ -102,7 +123,9 @@ class DirectAdminInventoryTests(SimpleTestCase):
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")]))
path = self.save(
make_tar([("backup/user.conf", "username=mailadmin\n")])
)
report = inspect_backup(path)
@@ -110,11 +133,18 @@ class DirectAdminInventoryTests(SimpleTestCase):
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):
@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
["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)))
@@ -124,7 +154,10 @@ class DirectAdminInventoryTests(SimpleTestCase):
def test_archive_requires_regular_and_unambiguous_account_metadata(self):
for entries, problem in (
([("backup/user.conf", None)], "Expected a DirectAdmin account backup"),
(
[("backup/user.conf", None)],
"Expected a DirectAdmin account backup",
),
(
[*self.entries, ("backup/user.conf", "username=other\n")],
"duplicate account or mailbox metadata",
@@ -140,7 +173,9 @@ class DirectAdminInventoryTests(SimpleTestCase):
path = self.save(make_tar(self.entries))
with (
patch("coulobre.directadmin.MAX_METADATA_SIZE", 4),
self.assertRaisesRegex(ValueError, "metadata file exceeds the size limit"),
self.assertRaisesRegex(
ValueError, "metadata file exceeds the size limit"
),
):
inspect_backup(path)
@@ -154,7 +189,9 @@ class DirectAdminInventoryTests(SimpleTestCase):
self.assertEqual(exit.exception.code, 1)
self.assertEqual(output.getvalue(), "")
self.assertIn("not a readable or complete tar archive", errors.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):
@@ -166,7 +203,9 @@ class DirectAdminInventoryTests(SimpleTestCase):
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 = bytearray(
make_tar([("backup/user.conf", "username=customer\n")])
)
archive[2 * tarfile.BLOCKSIZE] = ord("x")
with self.assertRaisesRegex(
+61 -20
View File
@@ -29,8 +29,14 @@ class DirectAdminImportPlanTests(TestCase):
("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/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"),
@@ -58,19 +64,27 @@ class DirectAdminImportPlanTests(TestCase):
def run_import(self, entries=None):
self.write_backup(entries)
self.import_output = StringIO()
call_command("import_directadmin", self.backup, stdout=self.import_output)
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):
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"}
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"}]
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 (
@@ -143,7 +157,11 @@ class DirectAdminImportPlanTests(TestCase):
self.assertEqual(
plan["conflicts"],
[
{"kind": "dns_zone", "domain": "example.net", "account_id": owner.pk},
{
"kind": "dns_zone",
"domain": "example.net",
"account_id": owner.pk,
},
{
"kind": "mail_domain",
"domain": "example.net",
@@ -162,21 +180,29 @@ class DirectAdminImportPlanTests(TestCase):
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"])
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")])
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(
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(
def test_import_creates_requests_and_reuses_the_account_on_replay(
self,
):
first = self.run_import()
@@ -210,7 +236,9 @@ class DirectAdminImportPlanTests(TestCase):
"support@example.net",
)
self.assertEqual(first["mailbox_requests"], ["support@example.net"])
self.assertEqual(DirectAdminImport.objects.get().account_id, account.pk)
self.assertEqual(
DirectAdminImport.objects.get().account_id, account.pk
)
self.assertFalse(HostingDnsZone.objects.exists())
self.assertNotIn("private-mail-hash", self.import_output.getvalue())
@@ -233,10 +261,15 @@ class DirectAdminImportPlanTests(TestCase):
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."),
"coulobre.hosting.directadmin_import."
"HostingMailbox.objects.bulk_create",
side_effect=IntegrityError(
"Interrupted while saving mailboxes."
),
),
self.assertRaisesRegex(
CommandError, "database rejected the import"
),
self.assertRaisesRegex(CommandError, "database rejected the import"),
):
self.run_import()
@@ -251,8 +284,14 @@ class DirectAdminImportPlanTests(TestCase):
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}
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",
@@ -277,6 +316,8 @@ class DirectAdminImportPlanTests(TestCase):
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.assertIn(
"missing one or more original requests", result["problems"][0]
)
self.assertFalse(HostingDatabase.objects.exists())
self.assertEqual(HostingAccount.objects.count(), 1)
@@ -22,18 +22,35 @@ class DirectAdminWebsiteTests(SimpleTestCase):
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/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"),
(
"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):
def test_stage_command_copies_only_the_selected_site_to_a_private_dir(
self,
):
self.write_backup(self.entries)
output = self.enterContext(redirect_stdout(StringIO()))
self.assertEqual(
@@ -57,9 +74,12 @@ class DirectAdminWebsiteTests(SimpleTestCase):
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"
(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())
@@ -74,7 +94,10 @@ class DirectAdminWebsiteTests(SimpleTestCase):
self.write_backup(self.entries)
report = stage_website(
self.backup, "bücher.example", self.destination, source_root="private_html"
self.backup,
"bücher.example",
self.destination,
source_root="private_html",
)
self.assertEqual(report["source_root"], "private_html")
@@ -106,7 +129,9 @@ class DirectAdminWebsiteTests(SimpleTestCase):
self.assertFalse(self.destination.exists())
def test_canonical_domains_cannot_select_two_distinct_source_directories(self):
def test_canonical_domains_cannot_select_two_distinct_source_directories(
self,
):
self.write_backup(
[
*self.entries,
+60 -14
View File
@@ -43,9 +43,12 @@ class DnsZoneManifestTests(SimpleTestCase):
self.assertEqual(zone.manifest()["version"], 1)
self.assertEqual(DnsZone.from_manifest(zone.manifest()), zone)
def test_accepts_a_single_external_nameserver_without_address_records(self):
def test_accepts_a_single_external_nameserver_without_address_records(
self,
):
zone = DnsZone.from_manifest(
self.manifest | {"nameservers": ["dns.provider.example"], "addresses": []}
self.manifest
| {"nameservers": ["dns.provider.example"], "addresses": []}
)
self.assertEqual(zone.nameservers, ("dns.provider.example",))
self.assertEqual(zone.addresses, ())
@@ -55,13 +58,21 @@ class DnsZoneManifestTests(SimpleTestCase):
({"addresses": []}, "in-zone nameserver needs an address"),
({"nameservers": []}, "Supply at least one nameserver"),
(
{"nameservers": ["DNS1.provider.example", "dns1.provider.example."]},
{
"nameservers": [
"DNS1.provider.example",
"dns1.provider.example.",
]
},
"list each name once",
),
(
{
"addresses": [
{"name": "other-bücher.example", "address": "192.0.2.30"}
{
"name": "other-bücher.example",
"address": "192.0.2.30",
}
]
},
"must belong to the zone",
@@ -82,8 +93,16 @@ class DnsZoneManifestTests(SimpleTestCase):
{"serial": -1},
{"serial": 2**32},
{"nameservers": "dns.provider.example"},
{"responsible_name": "hostmaster.provider.example\n$INCLUDE local.file"},
{"addresses": [{"name": "bücher.example", "address": "fe80::1%eth0"}]},
{
"responsible_name": (
"hostmaster.provider.example\n$INCLUDE local.file"
)
},
{
"addresses": [
{"name": "bücher.example", "address": "fe80::1%eth0"}
]
},
{"addresses": [{"name": "bücher.example", "address": 3232235521}]},
{"extra": "value"},
):
@@ -117,11 +136,18 @@ class DnsZoneManifestTests(SimpleTestCase):
"priority": 10,
"exchange": "MX.Provider.Example.",
},
{"name": "parked.bücher.example", "priority": 0, "exchange": "."},
{
"name": "parked.bücher.example",
"priority": 0,
"exchange": ".",
},
],
"txt_records": [
{"name": "bücher.example", "text": "v=spf1 mx -all"},
{"name": "_DMARC.BÜCHER。Example.", "text": "v=DMARC1; p=none"},
{
"name": "_DMARC.BÜCHER。Example.",
"text": "v=DMARC1; p=none",
},
],
}
@@ -139,13 +165,20 @@ class DnsZoneManifestTests(SimpleTestCase):
)
def test_invalid_mail_records_are_rejected(self):
manifest = self.manifest | {"version": 2, "mx_records": [], "txt_records": []}
manifest = self.manifest | {
"version": 2,
"mx_records": [],
"txt_records": [],
}
mail = {
"name": "bücher.example",
"priority": 10,
"exchange": "mx.provider.example",
}
text = {"name": "mail._domainkey.bücher.example", "text": "v=DKIM1; p=abc"}
text = {
"name": "mail._domainkey.bücher.example",
"text": "v=DKIM1; p=abc",
}
for changes in (
{"version": 1},
{"mx_records": None},
@@ -154,13 +187,24 @@ class DnsZoneManifestTests(SimpleTestCase):
{"mx_records": [mail | {"exchange": "missing.bücher.example"}]},
{"mx_records": [mail | {"exchange": "."}]},
{"mx_records": [mail, mail | {"priority": 0, "exchange": "."}]},
{"txt_records": [text | {"name": "_domainkey.not-bücher.example"}]},
{"txt_records": [text | {"name": "_dmarc" + "_" * 64 + ".bücher.example"}]},
{
"txt_records": [
text | {"name": "_domainkey.not-bücher.example"}
]
},
{
"txt_records": [
text | {"name": "_dmarc" + "_" * 64 + ".bücher.example"}
]
},
{"txt_records": [text | {"text": ["multivalued"]}]},
{"txt_records": [text | {"text": "\ud800"}]},
{"txt_records": [text | {"text": "x" * 65535}]},
):
with self.subTest(changes=set(changes)), self.assertRaises(ValueError):
with (
self.subTest(changes=set(changes)),
self.assertRaises(ValueError),
):
DnsZone.from_manifest(manifest | changes)
def test_txt_values_are_escaped_and_split_by_encoded_byte_length(self):
@@ -173,7 +217,9 @@ class DnsZoneManifestTests(SimpleTestCase):
)
self.assertEqual(TxtRecord(owner, "").render(), f'{owner}. IN TXT ""')
def test_apply_request_accepts_a_large_zone_and_returns_only_its_identity(self):
def test_apply_request_accepts_a_large_zone_and_returns_only_its_identity(
self,
):
manifest = self.manifest | {
"version": 2,
"mx_records": [],
+32 -10
View File
@@ -30,17 +30,27 @@ class DnsZoneApplyTests(SimpleTestCase):
'allow-update { "none"; }; };'
)
self.commands = self.enterContext(patch("coulobre.dns_node_apply.run"))
self.enterContext(patch("coulobre.dns_node_apply.ZONE_DIRECTORY", directory))
self.enterContext(patch("coulobre.dns_node_apply.require_root_directory"))
self.enterContext(patch("coulobre.dns_node_apply.os.geteuid", return_value=0))
self.enterContext(
patch("coulobre.dns_node_apply.ZONE_DIRECTORY", directory)
)
self.enterContext(
patch("coulobre.dns_node_apply.require_root_directory")
)
self.enterContext(
patch("coulobre.dns_node_apply.os.geteuid", return_value=0)
)
self.enterContext(
patch(
"coulobre.dns_node_apply.read_root_file",
side_effect=lambda path, *, mode: path.read_text(encoding="utf-8"),
side_effect=lambda path, *, mode: path.read_text(
encoding="utf-8"
),
)
)
def test_failed_validation_preserves_existing_zone_file_and_registration(self):
def test_failed_validation_preserves_existing_zone_file_and_registration(
self,
):
self.path.write_text(zone_file(self.zone), encoding="utf-8")
self.commands.side_effect = [
self.registration,
@@ -51,11 +61,15 @@ class DnsZoneApplyTests(SimpleTestCase):
with self.assertRaisesRegex(ValueError, "failed validation"):
apply_zone(self.updated)
self.assertEqual(self.path.read_text(encoding="utf-8"), zone_file(self.zone))
self.assertEqual(
self.path.read_text(encoding="utf-8"), zone_file(self.zone)
)
self.assertEqual(list(self.path.parent.iterdir()), [self.path])
self.assertEqual(self.commands.call_args.args[0], "named-checkzone")
def test_reapplying_after_reload_failure_reuses_the_validated_zone_file(self):
def test_reapplying_after_reload_failure_reuses_the_validated_zone_file(
self,
):
self.path.write_text(zone_file(self.zone), encoding="utf-8")
self.commands.side_effect = [
self.registration,
@@ -67,9 +81,16 @@ class DnsZoneApplyTests(SimpleTestCase):
with self.assertRaisesRegex(ValueError, "Reload interrupted"):
apply_zone(self.updated)
self.assertEqual(self.path.read_text(encoding="utf-8"), zone_file(self.updated))
self.assertEqual(
self.path.read_text(encoding="utf-8"), zone_file(self.updated)
)
self.commands.reset_mock()
self.commands.side_effect = [self.registration, "serial: 1", "", "serial: 2"]
self.commands.side_effect = [
self.registration,
"serial: 1",
"",
"serial: 2",
]
apply_zone(self.updated)
self.assertEqual(
@@ -83,7 +104,8 @@ class DnsZoneApplyTests(SimpleTestCase):
def test_unmanaged_running_zone_blocks_installation(self):
self.commands.return_value = (
'zone "example.net" { type primary; file "/etc/bind/existing.example"; };'
'zone "example.net" { type primary; '
'file "/etc/bind/existing.example"; };'
)
with self.assertRaisesRegex(ValueError, "outside Coulobre"):
+44 -15
View File
@@ -42,11 +42,15 @@ class DnsPublicationTests(TestCase):
self.url = reverse("panel:dns_zone_publish", args=[self.zone.pk])
self.detail = self.account.get_absolute_url()
def test_queued_snapshot_survives_edits_and_the_new_revision_can_publish_next(self):
def test_queued_snapshot_survives_edits_and_next_revision_can_publish(
self,
):
self.assertContains(self.client.get(self.detail), "Publish zone")
self.assertEqual(self.client.get(self.url).status_code, 405)
for _ in range(2):
self.assertRedirects(self.client.post(self.url, {"serial": 1}), self.detail)
self.assertRedirects(
self.client.post(self.url, {"serial": 1}), self.detail
)
publication = DnsPublication.objects.get(zone=self.zone)
self.assertContains(self.client.get(self.detail), "Queued serial 1")
with patch.object(publish_dns_zone, "apply_async") as send:
@@ -71,7 +75,9 @@ class DnsPublicationTests(TestCase):
)
self.zone.refresh_from_db()
self.assertEqual(self.zone.serial, 2)
self.assertEqual(self.client.post(self.url, {"serial": 1}).status_code, 409)
self.assertEqual(
self.client.post(self.url, {"serial": 1}).status_code, 409
)
self.client.post(self.url, {"serial": 2})
publication.refresh_from_db()
self.assertEqual(publication.serial, 1)
@@ -85,7 +91,9 @@ class DnsPublicationTests(TestCase):
self.assertContains(detail, "Published SOA serial 1")
self.assertContains(detail, "Publish zone")
self.assertRedirects(self.client.post(self.url, {"serial": 2}), self.detail)
self.assertRedirects(
self.client.post(self.url, {"serial": 2}), self.detail
)
publication.refresh_from_db()
self.assertEqual(publication.published_serial, 1)
self.assertEqual(publication.serial, 2)
@@ -98,13 +106,19 @@ class DnsPublicationTests(TestCase):
self.assertContains(detail, "Published SOA serial 1")
self.assertContains(detail, "Publishing failed for serial 2")
self.assertContains(detail, "Retry publishing")
self.assertRedirects(self.client.post(self.url, {"serial": 2}), self.detail)
self.assertRedirects(
self.client.post(self.url, {"serial": 2}), self.detail
)
with patch("coulobre.hosting.tasks.publish_local_zone") as apply:
publish_dns_zone.run(publication.pk)
apply.assert_called_once_with(self.zone.spec)
self.assertContains(self.client.get(self.detail), "Published SOA serial 2")
self.assertContains(
self.client.get(self.detail), "Published SOA serial 2"
)
def test_customer_and_operator_without_publish_permission_cannot_queue(self):
def test_customer_and_operator_without_publish_permission_cannot_queue(
self,
):
viewer = get_user_model().objects.create_user("viewer")
viewer.user_permissions.add(
*Permission.objects.filter(
@@ -114,7 +128,9 @@ class DnsPublicationTests(TestCase):
for user in (self.customer, viewer):
with self.subTest(user=user):
self.client.force_login(user)
self.assertNotContains(self.client.get(self.detail), "Publish zone")
self.assertNotContains(
self.client.get(self.detail), "Publish zone"
)
self.assertEqual(
self.client.post(self.url, {"serial": 1}).status_code, 403
)
@@ -123,7 +139,9 @@ class DnsPublicationTests(TestCase):
@override_settings(LOCAL_DNS_PUBLISHING=False)
def test_disabled_publishing_keeps_manifest_downloads_available(self):
self.assertNotContains(self.client.get(self.detail), "Publish zone")
self.assertEqual(self.client.post(self.url, {"serial": 1}).status_code, 404)
self.assertEqual(
self.client.post(self.url, {"serial": 1}).status_code, 404
)
manifest_url = reverse("panel:dns_zone_manifest", args=[self.zone.pk])
self.assertEqual(
self.client.get(manifest_url).json(), self.zone.spec.manifest()
@@ -133,9 +151,15 @@ class DnsPublicationTests(TestCase):
class DnsPublicationSocketTests(SimpleTestCase):
def test_receipt_must_identify_the_exact_soa_serial(self):
zone = DnsZone(
"site.example", 1, ("ns.provider.example",), "hostmaster.site.example"
"site.example",
1,
("ns.provider.example",),
"hostmaster.site.example",
)
reply = zone.manifest_identity() | {"state": "configured", "problem": None}
reply = zone.manifest_identity() | {
"state": "configured",
"problem": None,
}
with patch("coulobre.hosting.node_client.socket.socket") as socket:
connection = socket.return_value.__enter__.return_value
read = connection.makefile.return_value.__enter__
@@ -144,9 +168,14 @@ class DnsPublicationSocketTests(SimpleTestCase):
BytesIO(json.dumps(reply | {"serial": True}).encode()),
)
publish_local_zone(zone)
connection.connect.assert_called_once_with("/run/coulobre-dns-apply.sock")
self.assertEqual(
json.loads(connection.sendall.call_args.args[0]), zone.manifest()
connection.connect.assert_called_once_with(
"/run/coulobre-dns-apply.sock"
)
with self.assertRaisesMessage(ValueError, "invalid response for this zone"):
self.assertEqual(
json.loads(connection.sendall.call_args.args[0]),
zone.manifest(),
)
with self.assertRaisesMessage(
ValueError, "invalid response for this zone"
):
publish_local_zone(zone)
+72 -26
View File
@@ -25,7 +25,9 @@ class DnsZonePanelTests(TestCase):
)
reseller = Reseller.objects.create(user=cls.reseller_user)
cls.account = HostingAccount.objects.create(
name="Account A", primary_domain="account-a.example", reseller=reseller
name="Account A",
primary_domain="account-a.example",
reseller=reseller,
)
cls.other = HostingAccount.objects.create(
name="Account B", primary_domain="account-b.example"
@@ -51,7 +53,9 @@ class DnsZonePanelTests(TestCase):
)
return self.account.dns_zones.get()
def test_operator_can_create_a_zone_and_download_its_renderable_manifest(self):
def test_operator_can_create_a_zone_and_download_its_renderable_manifest(
self,
):
self.assertContains(self.client.get(self.add_url), "Add DNS zone")
zone = self.create_zone()
self.assertEqual(zone.domain, self.account.primary_domain)
@@ -64,21 +68,29 @@ class DnsZonePanelTests(TestCase):
self.assertContains(account, f"Edit DNS zone for {zone.domain}")
self.assertNotContains(account, self.add_url)
manifest = self.client.get(reverse("panel:dns_zone_manifest", args=[zone.pk]))
manifest = self.client.get(
reverse("panel:dns_zone_manifest", args=[zone.pk])
)
self.assertEqual(manifest["Cache-Control"], "private, no-store")
self.assertIn("attachment", manifest["Content-Disposition"])
self.assertEqual(manifest.json()["version"], 1)
spec = DnsZone.from_manifest(manifest.json())
self.assertEqual(spec, zone.spec)
self.assertIn("www.account-a.example. IN AAAA 2001:db8::20\n", spec.render())
self.assertIn(
"www.account-a.example. IN AAAA 2001:db8::20\n", spec.render()
)
def test_operator_can_create_mail_records_and_download_a_version_two_manifest(self):
def test_operator_can_add_mail_records_and_download_a_v2_manifest(
self,
):
form = self.client.get(self.add_url)
self.assertContains(form, "MX records")
self.assertContains(form, "TXT records")
dkim = "v=DKIM1; p=" + "A" * 340
mail_settings = {
"mx_records": "@ 20 NS1.Account-A.Example.\n@ 10 mx.provider.example",
"mx_records": (
"@ 20 NS1.Account-A.Example.\n@ 10 mx.provider.example"
),
"txt_records": (
"@ v=spf1 mx -all\n"
"_DMARC.Account-A.Example. v=DMARC1; p=none\n"
@@ -104,11 +116,13 @@ class DnsZonePanelTests(TestCase):
"exchange": "ns1.account-a.example",
},
)
self.assertEqual(manifest["txt_records"][1]["name"], "_dmarc.account-a.example")
self.assertEqual(
manifest["txt_records"][1]["name"], "_dmarc.account-a.example"
)
self.assertEqual(manifest["txt_records"][2]["text"], dkim)
self.assertEqual(DnsZone.from_manifest(manifest), zone.spec)
def test_adding_and_removing_mail_records_changes_the_serial_and_manifest_version(
def test_adding_and_removing_mail_records_updates_serial_and_version(
self,
):
zone = self.create_zone()
@@ -131,7 +145,9 @@ class DnsZonePanelTests(TestCase):
)
manifest = self.client.get(export).json()
self.assertEqual((manifest["version"], manifest["serial"]), (2, 2))
self.assertEqual([item["text"] for item in manifest["txt_records"]], [text, ""])
self.assertEqual(
[item["text"] for item in manifest["txt_records"]], [text, ""]
)
unchanged = self.client.get(edit).context["form"].initial
self.assertRedirects(
@@ -141,7 +157,9 @@ class DnsZonePanelTests(TestCase):
self.assertEqual(self.client.get(export).json(), manifest)
self.assertRedirects(
self.client.post(edit, unchanged | {"mx_records": "", "txt_records": ""}),
self.client.post(
edit, unchanged | {"mx_records": "", "txt_records": ""}
),
self.account.get_absolute_url(),
)
manifest = self.client.get(export).json()
@@ -161,7 +179,10 @@ class DnsZonePanelTests(TestCase):
{"mx_records": "@ 10 missing.account-a.example"},
"MX exchange needs an address",
),
({"txt_records": '@ "unclosed text'}, "Enter a valid quoted JSON string"),
(
{"txt_records": '@ "unclosed text'},
"Enter a valid quoted JSON string",
),
(
{"txt_records": "_dmarc.other.example v=DMARC1"},
"records must belong to the zone",
@@ -169,7 +190,9 @@ class DnsZonePanelTests(TestCase):
):
with self.subTest(fields=fields):
self.assertContains(
self.client.post(edit, self.zone_data | {"serial": 1} | fields),
self.client.post(
edit, self.zone_data | {"serial": 1} | fields
),
message,
)
zone.refresh_from_db()
@@ -177,21 +200,32 @@ class DnsZonePanelTests(TestCase):
self.assertEqual(zone.mx_records, [])
self.assertEqual(zone.txt_records, [])
def test_duplicate_and_invalid_zones_leave_the_current_zone_unchanged(self):
invalid = self.client.post(self.add_url, self.zone_data | {"addresses": ""})
self.assertContains(invalid, "Each in-zone nameserver needs an address record.")
def test_duplicate_and_invalid_zones_leave_the_current_zone_unchanged(
self,
):
invalid = self.client.post(
self.add_url, self.zone_data | {"addresses": "ns1.account-a.example"}
self.add_url, self.zone_data | {"addresses": ""}
)
self.assertContains(
invalid, "Each in-zone nameserver needs an address record."
)
invalid = self.client.post(
self.add_url,
self.zone_data | {"addresses": "ns1.account-a.example"},
)
self.assertContains(
invalid, "Enter a name and an IP address on line 1."
)
self.assertContains(invalid, "Enter a name and an IP address on line 1.")
self.assertFalse(HostingDnsZone.objects.exists())
zone = self.create_zone()
duplicate = self.client.post(self.add_url, self.zone_data)
self.assertContains(duplicate, "A DNS zone already exists for this domain.")
self.assertContains(
duplicate, "A DNS zone already exists for this domain."
)
self.assertEqual(self.account.dns_zones.get().pk, zone.pk)
def test_edit_increments_serial_only_when_data_changes_and_rejects_stale_edits(
def test_edit_increments_serial_on_changes_and_rejects_stale_edits(
self,
):
zone = self.create_zone()
@@ -208,14 +242,18 @@ class DnsZonePanelTests(TestCase):
self.assertEqual(zone.serial, 1)
updated = self.zone_data | {
"addresses": self.zone_data["addresses"].replace("192.0.2.20", "192.0.2.21")
"addresses": self.zone_data["addresses"].replace(
"192.0.2.20", "192.0.2.21"
)
}
self.assertRedirects(
self.client.post(edit, updated | {"serial": 1}),
self.account.get_absolute_url(),
)
stale = self.client.post(edit, self.zone_data | {"serial": 1})
self.assertContains(stale, "This DNS zone changed while you were editing it.")
self.assertContains(
stale, "This DNS zone changed while you were editing it."
)
manifest = self.client.get(
reverse("panel:dns_zone_manifest", args=[zone.pk])
).json()
@@ -239,7 +277,7 @@ class DnsZonePanelTests(TestCase):
zone.refresh_from_db()
self.assertEqual(zone.serial, 0)
def test_renaming_account_keeps_its_existing_zone_and_allows_a_new_primary_zone(
def test_renaming_account_preserves_its_zone_and_allows_new_primary(
self,
):
zone = self.create_zone()
@@ -265,7 +303,9 @@ class DnsZonePanelTests(TestCase):
["account-a.example", "new.example"],
)
def test_reseller_cannot_edit_or_download_even_with_django_permissions(self):
def test_reseller_cannot_edit_or_download_even_with_django_permissions(
self,
):
zone = self.create_zone()
self.reseller_user.user_permissions.set(
Permission.objects.filter(content_type__app_label="hosting")
@@ -282,7 +322,9 @@ class DnsZonePanelTests(TestCase):
self.client.post(self.add_url, self.zone_data).status_code, 403
)
self.assertEqual(
self.client.get(reverse("panel:dns_zone_edit", args=[zone.pk])).status_code,
self.client.get(
reverse("panel:dns_zone_edit", args=[zone.pk])
).status_code,
403,
)
self.assertEqual(
@@ -299,11 +341,15 @@ class DnsZonePanelTests(TestCase):
self.assertContains(account, "Download DNS manifest")
self.assertNotContains(account, "Edit DNS zone")
self.assertContains(
self.client.get(reverse("panel:dns_zone_manifest", args=[zone.pk])),
self.client.get(
reverse("panel:dns_zone_manifest", args=[zone.pk])
),
zone.domain,
)
self.assertEqual(
self.client.get(reverse("panel:dns_zone_edit", args=[zone.pk])).status_code,
self.client.get(
reverse("panel:dns_zone_edit", args=[zone.pk])
).status_code,
403,
)
self.assertEqual(self.client.get(self.add_url).status_code, 403)
+30 -9
View File
@@ -71,7 +71,9 @@ class HostingPlanTests(TestCase):
self.assertIsNone(plan.database_limit)
self.assertEqual(plan.mailbox_limit, 2)
self.assertContains(self.client.get(list_url), "Unlimited")
self.assertContains(self.client.get(reverse("panel:accounts")), "Standard")
self.assertContains(
self.client.get(reverse("panel:accounts")), "Standard"
)
response = self.client.post(
reverse("panel:account_create"),
@@ -89,16 +91,24 @@ class HostingPlanTests(TestCase):
self.client.force_login(self.operator)
response = self.client.post(
reverse("panel:hosting_plan_create"),
{"name": "Invalid plan", "database_limit": -1, "mailbox_limit": -2},
{
"name": "Invalid plan",
"database_limit": -1,
"mailbox_limit": -2,
},
)
self.assertIn("database_limit", response.context["form"].errors)
self.assertIn("mailbox_limit", response.context["form"].errors)
self.assertFalse(HostingPlan.objects.exists())
def test_editor_without_plan_permission_cannot_assign_in_either_interface(self):
def test_editor_without_plan_permission_cannot_assign_in_either_interface(
self,
):
current = HostingPlan.objects.create(name="Private plan")
other = HostingPlan.objects.create(name="Other plan")
HostingAccount.objects.filter(pk=self.account.pk).update(hosting_plan=current)
HostingAccount.objects.filter(pk=self.account.pk).update(
hosting_plan=current
)
self.client.force_login(self.editor)
self.assertEqual(
self.client.get(reverse("panel:hosting_plans")).status_code, 403
@@ -107,10 +117,15 @@ class HostingPlanTests(TestCase):
self.client.get(self.account.get_absolute_url()), current.name
)
for route in ("panel:account_edit", "admin:hosting_hostingaccount_change"):
for route in (
"panel:account_edit",
"admin:hosting_hostingaccount_change",
):
with self.subTest(route=route):
url = reverse(route, args=[self.account.pk])
self.assertNotContains(self.client.get(url), 'name="hosting_plan"')
self.assertNotContains(
self.client.get(url), 'name="hosting_plan"'
)
response = self.client.post(
url,
{
@@ -124,13 +139,17 @@ class HostingPlanTests(TestCase):
self.assertEqual(self.account.name, route)
self.assertEqual(self.account.hosting_plan_id, current.pk)
def test_unrelated_account_edit_preserves_a_concurrent_plan_assignment(self):
def test_unrelated_account_edit_preserves_a_concurrent_plan_assignment(
self,
):
plan = HostingPlan.objects.create(name="Starter")
self.client.force_login(self.editor)
save = HostingAccount.save
def assign_then_save(account, *args, **kwargs):
HostingAccount.objects.filter(pk=account.pk).update(hosting_plan=plan)
HostingAccount.objects.filter(pk=account.pk).update(
hosting_plan=plan
)
return save(account, *args, **kwargs)
with patch.object(HostingAccount, "save", assign_then_save):
@@ -145,7 +164,9 @@ class HostingPlanTests(TestCase):
def test_cannot_delete_an_assigned_plan(self):
plan = HostingPlan.objects.create(name="Assigned plan")
HostingAccount.objects.filter(pk=self.account.pk).update(hosting_plan=plan)
HostingAccount.objects.filter(pk=self.account.pk).update(
hosting_plan=plan
)
with self.assertRaises(ProtectedError):
plan.delete()
+85 -26
View File
@@ -49,10 +49,14 @@ class MailboxApplyRequestTests(SimpleTestCase):
code, reply = self.request(manifest)
self.apply.assert_called_once_with(self.mailbox)
self.assertEqual(code, 0)
self.assertEqual(reply, manifest | {"state": "configured", "problem": None})
self.assertEqual(
reply, manifest | {"state": "configured", "problem": None}
)
def test_request_rejects_extra_credentials_before_acting(self):
code, reply = self.request(self.mailbox.manifest() | {"password": "untrusted"})
code, reply = self.request(
self.mailbox.manifest() | {"password": "untrusted"}
)
self.assertEqual(code, 1)
self.assertEqual(reply["state"], "failed")
self.apply.assert_not_called()
@@ -75,7 +79,9 @@ class MailboxApplyTests(SimpleTestCase):
}
for name, value in settings.items():
self.enterContext(patch(f"coulobre.mail_node_apply.{name}", value))
self.enterContext(patch("coulobre.mail_node_apply.os.geteuid", return_value=0))
self.enterContext(
patch("coulobre.mail_node_apply.os.geteuid", return_value=0)
)
self.enterContext(
patch(
"coulobre.mail_node_apply.require_root_directory",
@@ -85,7 +91,9 @@ class MailboxApplyTests(SimpleTestCase):
self.enterContext(
patch(
"coulobre.mail_node_apply.read_root_file",
side_effect=lambda path, *, mode: path.read_text(encoding="utf-8"),
side_effect=lambda path, *, mode: path.read_text(
encoding="utf-8"
),
)
)
self.account = SimpleNamespace(pw_uid=1001, pw_gid=1001)
@@ -96,12 +104,17 @@ class MailboxApplyTests(SimpleTestCase):
)
)
self.resolve_home = self.enterContext(
patch("coulobre.mail_node_apply.dovecot_home", side_effect=self.lookup_home)
patch(
"coulobre.mail_node_apply.dovecot_home",
side_effect=self.lookup_home,
)
)
self.prepare_home = self.enterContext(
patch("coulobre.mail_node_apply.ensure_mail_home")
)
self.commands = self.enterContext(patch("coulobre.mail_node_apply.run"))
self.commands = self.enterContext(
patch("coulobre.mail_node_apply.run")
)
self.commands.return_value = "{SHA512-CRYPT}$6$mockSalt$" + ("A" * 86)
self.postfix_lookup = self.enterContext(
patch("coulobre.mail_node_apply.postfix_lookup", return_value=None)
@@ -113,11 +126,16 @@ class MailboxApplyTests(SimpleTestCase):
path.mkdir(mode=create_mode, exist_ok=True)
def lookup_home(self, mailbox):
if self.users.exists() and f"{mailbox.address}:" in self.users.read_text():
if (
self.users.exists()
and f"{mailbox.address}:" in self.users.read_text()
):
return str(self.storage / mailbox.domain / mailbox.local_part)
return None
def test_reapplying_preserves_password_and_privately_publishes_the_hash(self):
def test_reapplying_preserves_password_and_privately_publishes_the_hash(
self,
):
credential_file = apply_mailbox(self.spec)
original = credential_file.read_bytes()
@@ -132,8 +150,12 @@ class MailboxApplyTests(SimpleTestCase):
self.assertIn("support@example.net\t1", self.mailboxes.read_text())
self.assertIn("example.net\t1", self.domains.read_text())
def test_pending_mailbox_is_published_only_after_its_home_is_prepared(self):
self.prepare_home.side_effect = ValueError("Interrupted before home creation.")
def test_pending_mailbox_is_published_only_after_its_home_is_prepared(
self,
):
self.prepare_home.side_effect = ValueError(
"Interrupted before home creation."
)
with self.assertRaisesRegex(ValueError, "Interrupted"):
apply_mailbox(self.spec)
credential_file = credential_path(self.spec)
@@ -160,12 +182,18 @@ class MailboxApplyTests(SimpleTestCase):
self.assertIn("support@example.net\t1", self.mailboxes.read_text())
def test_unmanaged_lookup_is_preserved_without_reserving_credentials(self):
self.mailboxes.write_text("existing@example.net\t1\n", encoding="utf-8")
self.mailboxes.write_text(
"existing@example.net\t1\n", encoding="utf-8"
)
with self.assertRaisesRegex(ValueError, "differ from Coulobre's registry"):
with self.assertRaisesRegex(
ValueError, "differ from Coulobre's registry"
):
apply_mailbox(self.spec)
self.assertEqual(self.mailboxes.read_text(), "existing@example.net\t1\n")
self.assertEqual(
self.mailboxes.read_text(), "existing@example.net\t1\n"
)
self.assertFalse(credential_path(self.spec).exists())
def test_missing_prepared_home_is_not_recreated(self):
@@ -181,14 +209,20 @@ class MailboxApplyTests(SimpleTestCase):
self.assertEqual(
result,
{"address": self.spec.address, "state": "not_installed", "problem": None},
{
"address": self.spec.address,
"state": "not_installed",
"problem": None,
},
)
self.assertFalse(self.state.exists())
self.assertFalse(self.storage.exists())
self.assertFalse(self.users.exists())
self.commands.assert_not_called()
def test_status_detects_a_live_recipient_without_a_credentials_record(self):
def test_status_detects_a_live_recipient_without_a_credentials_record(
self,
):
self.postfix_lookup.return_value = "1"
result = mailbox_status(self.spec)
@@ -197,7 +231,9 @@ class MailboxApplyTests(SimpleTestCase):
self.assertIn("outside Coulobre's registry", result["problem"])
def test_status_detects_a_pending_home_preparation(self):
self.prepare_home.side_effect = ValueError("Interrupted before home creation.")
self.prepare_home.side_effect = ValueError(
"Interrupted before home creation."
)
with self.assertRaisesRegex(ValueError, "Interrupted"):
apply_mailbox(self.spec)
@@ -206,7 +242,9 @@ class MailboxApplyTests(SimpleTestCase):
self.assertEqual(result["state"], "needs_attention")
self.assertIn("installation is incomplete", result["problem"])
def test_status_runs_local_authentication_with_saved_password_on_stdin(self):
def test_status_runs_local_authentication_with_saved_password_on_stdin(
self,
):
path = apply_mailbox(self.spec)
saved = json.loads(path.read_text())
self.postfix_lookup.return_value = "1"
@@ -225,7 +263,9 @@ class MailboxApplyTests(SimpleTestCase):
standard_input=saved["password"] + "\n",
)
def test_status_detects_a_recipient_missing_from_the_active_postfix_map(self):
def test_status_detects_a_recipient_missing_from_the_active_postfix_map(
self,
):
apply_mailbox(self.spec)
self.postfix_lookup.side_effect = ["1", None]
self.commands.reset_mock()
@@ -236,7 +276,9 @@ class MailboxApplyTests(SimpleTestCase):
self.assertIn("Postfix did not resolve", result["problem"])
self.commands.assert_not_called()
def test_status_command_reports_auth_failure_without_exposing_credentials(self):
def test_status_command_reports_auth_failure_without_exposing_credentials(
self,
):
path = apply_mailbox(self.spec)
saved = json.loads(path.read_text())
self.postfix_lookup.return_value = "1"
@@ -252,7 +294,8 @@ class MailboxApplyTests(SimpleTestCase):
report = json.loads(output.getvalue())
self.assertEqual(report["state"], "needs_attention")
self.assertEqual(
report["problem"], "Dovecot could not authenticate the saved mailbox login."
report["problem"],
"Dovecot could not authenticate the saved mailbox login.",
)
self.assertNotIn(saved["password"], output.getvalue())
self.assertNotIn(saved["password_hash"], output.getvalue())
@@ -270,8 +313,13 @@ class MailboxCommandTests(SimpleTestCase):
for settings in (["mdbox"], ["maildir", "~/other"]):
with (
self.subTest(settings=settings),
patch("coulobre.mail_node_apply.run", side_effect=["2.4.2", *settings]),
self.assertRaisesMessage(ValueError, "mail_driver and mail_path"),
patch(
"coulobre.mail_node_apply.run",
side_effect=["2.4.2", *settings],
),
self.assertRaisesMessage(
ValueError, "mail_driver and mail_path"
),
):
check_dovecot_maildir()
@@ -293,19 +341,30 @@ class MailboxCommandTests(SimpleTestCase):
command, 75, "secret hash", "secret password"
),
),
self.assertRaisesRegex(ValueError, r"^doveadm pw failed \(75\)\.$"),
self.assertRaisesRegex(
ValueError, r"^doveadm pw failed \(75\)\.$"
),
):
run(*command, standard_input="secret password")
def test_postfix_query_error_is_distinct_from_a_missing_key(self):
command = ("postmap", "-q", "support@example.net", "proxy:texthash:/mailboxes")
command = (
"postmap",
"-q",
"support@example.net",
"proxy:texthash:/mailboxes",
)
with patch(
"coulobre.mail_node_apply.subprocess.run",
side_effect=[
CompletedProcess(command, 1, "", ""),
CompletedProcess(command, 1, "", "postmap: fatal: unavailable"),
CompletedProcess(
command, 1, "", "postmap: fatal: unavailable"
),
],
):
self.assertIsNone(run(*command, missing_exit=1, missing_output=""))
with self.assertRaisesRegex(ValueError, "postmap: fatal: unavailable"):
with self.assertRaisesRegex(
ValueError, "postmap: fatal: unavailable"
):
run(*command, missing_exit=1, missing_output="")
@@ -93,9 +93,13 @@ class MailboxProvisioningTests(TestCase):
@override_settings(LOCAL_MAILBOX_PROVISIONING=False)
def test_disabled_provisioning_leaves_manifest_downloads_available(self):
self.assertNotContains(self.client.get(self.detail), "Provision mailbox")
self.assertNotContains(
self.client.get(self.detail), "Provision mailbox"
)
self.assertEqual(self.client.post(self.url).status_code, 404)
manifest_url = reverse("panel:mailbox_manifest", args=[self.mailbox.pk])
manifest_url = reverse(
"panel:mailbox_manifest", args=[self.mailbox.pk]
)
self.assertEqual(
self.client.get(manifest_url).json(), self.mailbox.spec.manifest()
)
@@ -104,7 +108,8 @@ class MailboxProvisioningTests(TestCase):
self.assertRedirects(self.client.post(self.url), self.detail)
job = MailboxProvisioning.objects.get(mailbox=self.mailbox)
with patch(
"coulobre.hosting.tasks.provision_local_mailbox", side_effect=OSError
"coulobre.hosting.tasks.provision_local_mailbox",
side_effect=OSError,
):
provision_mailbox.run(job.pk)
detail = self.client.get(self.detail)
+56 -20
View File
@@ -27,7 +27,9 @@ class MailboxRequestTests(TestCase):
cls.reseller_user = users.create_user("reseller")
reseller = Reseller.objects.create(user=cls.reseller_user)
cls.account = HostingAccount.objects.create(
name="Account A", primary_domain="Bücher.Example", reseller=reseller
name="Account A",
primary_domain="Bücher.Example",
reseller=reseller,
)
cls.other = HostingAccount.objects.create(
name="Account B", primary_domain="other.example"
@@ -35,7 +37,9 @@ class MailboxRequestTests(TestCase):
def setUp(self):
self.client.force_login(self.operator)
self.request_url = reverse("panel:mailbox_create", args=[self.account.pk])
self.request_url = reverse(
"panel:mailbox_create", args=[self.account.pk]
)
def request_mailbox(self, local_part="Support.Team"):
self.assertRedirects(
@@ -45,13 +49,19 @@ class MailboxRequestTests(TestCase):
return HostingMailbox.objects.get()
def test_operator_can_request_a_mailbox_and_download_its_manifest(self):
self.assertContains(self.client.get(self.request_url), "Request mailbox")
self.assertContains(
self.client.get(self.request_url), "Request mailbox"
)
mailbox = self.request_mailbox()
self.assertEqual(mailbox.mail_domain.account, self.account)
address = "support.team@xn--bcher-kva.example"
self.assertContains(self.client.get(self.account.get_absolute_url()), address)
self.assertContains(
self.client.get(self.account.get_absolute_url()), address
)
manifest = self.client.get(reverse("panel:mailbox_manifest", args=[mailbox.pk]))
manifest = self.client.get(
reverse("panel:mailbox_manifest", args=[mailbox.pk])
)
self.assertEqual(manifest["Cache-Control"], "private, no-store")
self.assertIn("attachment", manifest["Content-Disposition"])
self.assertEqual(
@@ -63,12 +73,20 @@ class MailboxRequestTests(TestCase):
"local_part": "support.team",
},
)
self.assertEqual(MailboxSpec.from_manifest(manifest.json()).address, address)
self.assertEqual(
MailboxSpec.from_manifest(manifest.json()).address, address
)
def test_duplicate_local_parts_are_case_insensitive_and_scoped_by_domain(self):
def test_duplicate_local_parts_are_case_insensitive_and_scoped_by_domain(
self,
):
self.request_mailbox("Support")
duplicate = self.client.post(self.request_url, {"local_part": "support"})
self.assertContains(duplicate, "This mailbox has already been requested.")
duplicate = self.client.post(
self.request_url, {"local_part": "support"}
)
self.assertContains(
duplicate, "This mailbox has already been requested."
)
self.assertRedirects(
self.client.post(
@@ -80,14 +98,20 @@ class MailboxRequestTests(TestCase):
self.assertEqual(HostingMailbox.objects.count(), 2)
def test_invalid_request_leaves_the_domain_available(self):
response = self.client.post(self.request_url, {"local_part": "support+tag"})
response = self.client.post(
self.request_url, {"local_part": "support+tag"}
)
self.assertIn("local_part", response.context["form"].errors)
self.assertFalse(HostingMailDomain.objects.exists())
def test_mailbox_quota_counts_old_domains_and_preserves_existing_requests(self):
def test_mailbox_quota_counts_old_domains_and_preserves_existing_requests(
self,
):
plan = HostingPlan.objects.create(name="Solo mail", mailbox_limit=1)
HostingAccount.objects.filter(pk=self.account.pk).update(hosting_plan=plan)
HostingAccount.objects.filter(pk=self.account.pk).update(
hosting_plan=plan
)
original = self.request_mailbox("support")
response = self.client.post(
reverse("panel:account_edit", args=[self.account.pk]),
@@ -117,10 +141,13 @@ class MailboxRequestTests(TestCase):
self.account.get_absolute_url(),
)
self.assertEqual(
HostingMailbox.objects.get(local_part="billing").spec.domain, "new.example"
HostingMailbox.objects.get(local_part="billing").spec.domain,
"new.example",
)
def test_renamed_account_keeps_existing_mail_and_prevents_domain_reassignment(self):
def test_renaming_account_keeps_mail_and_prevents_domain_reassignment(
self,
):
original = self.request_mailbox("support")
mail_domain = original.mail_domain.domain
self.assertRedirects(
@@ -131,14 +158,16 @@ class MailboxRequestTests(TestCase):
self.account.get_absolute_url(),
)
self.assertContains(
self.client.get(self.account.get_absolute_url()), f"support@{mail_domain}"
self.client.get(self.account.get_absolute_url()),
f"support@{mail_domain}",
)
self.assertRedirects(
self.client.post(self.request_url, {"local_part": "billing"}),
self.account.get_absolute_url(),
)
self.assertEqual(
HostingMailbox.objects.get(local_part="billing").spec.domain, "new.example"
HostingMailbox.objects.get(local_part="billing").spec.domain,
"new.example",
)
HostingAccount.objects.filter(pk=self.other.pk).update(
@@ -158,7 +187,9 @@ class MailboxRequestTests(TestCase):
other_domain = HostingMailDomain.objects.create(
account=self.other, domain="other.example"
)
HostingMailbox.objects.create(mail_domain=other_domain, local_part="other")
HostingMailbox.objects.create(
mail_domain=other_domain, local_part="other"
)
self.client.force_login(self.reseller_user)
account = self.client.get(self.account.get_absolute_url())
@@ -170,7 +201,9 @@ class MailboxRequestTests(TestCase):
self.client.get(self.other.get_absolute_url()).status_code, 404
)
self.assertEqual(
self.client.post(self.request_url, {"local_part": "another"}).status_code,
self.client.post(
self.request_url, {"local_part": "another"}
).status_code,
403,
)
self.assertEqual(
@@ -193,10 +226,13 @@ class MailboxManifestTests(SimpleTestCase):
self.assertEqual(main(["inspect", str(path)]), 0)
self.assertEqual(
json.loads(output.getvalue()), {"address": "support@xn--bcher-kva.example"}
json.loads(output.getvalue()),
{"address": "support@xn--bcher-kva.example"},
)
def test_manifest_rejects_invalid_recipient_keys_and_unexpected_fields(self):
def test_manifest_rejects_invalid_recipient_keys_and_unexpected_fields(
self,
):
manifest = MailboxSpec("example.net", "support").manifest()
for change in (
{"version": True},
+22 -8
View File
@@ -12,11 +12,14 @@ class PanelTests(TestCase):
def setUpTestData(cls):
users = get_user_model().objects
cls.login_password = "test-only-coulobre-password"
cls.operator = users.create_superuser("operator", password=cls.login_password)
cls.operator = users.create_superuser(
"operator", password=cls.login_password
)
cls.viewer = users.create_user("viewer")
cls.viewer.user_permissions.add(
Permission.objects.get(
content_type__app_label="hosting", codename="view_hostingaccount"
content_type__app_label="hosting",
codename="view_hostingaccount",
)
)
cls.account = HostingAccount.objects.create(
@@ -29,7 +32,9 @@ class PanelTests(TestCase):
self.assertRedirects(
self.client.get(account_url), f"{login_url}?next={account_url}"
)
self.assertContains(self.client.get(login_url), "/static/hosting/panel.css")
self.assertContains(
self.client.get(login_url), "/static/hosting/panel.css"
)
response = self.client.post(
login_url,
@@ -40,7 +45,9 @@ class PanelTests(TestCase):
},
)
self.assertRedirects(response, account_url)
self.assertRedirects(self.client.post(reverse("panel:logout")), login_url)
self.assertRedirects(
self.client.post(reverse("panel:logout")), login_url
)
self.assertRedirects(
self.client.get(account_url), f"{login_url}?next={account_url}"
)
@@ -54,7 +61,9 @@ class PanelTests(TestCase):
account = HostingAccount.objects.get(name="Test tenant")
self.assertRedirects(response, account.get_absolute_url())
response = self.client.get(reverse("panel:accounts"), {"q": "test-tenant"})
response = self.client.get(
reverse("panel:accounts"), {"q": "test-tenant"}
)
self.assertContains(response, "test-tenant.example")
self.assertNotContains(response, "example.org")
@@ -78,7 +87,9 @@ class PanelTests(TestCase):
render_web_plan.run(plan.pk)
self.assertContains(self.client.get(preview_url), "ServerName example.org")
self.assertContains(
self.client.get(preview_url), "ServerName example.org"
)
self.assertContains(self.client.get(reverse("panel:plans")), "Ready")
def test_viewer_cannot_mutate_accounts_or_read_previews(self):
@@ -104,14 +115,17 @@ class PanelTests(TestCase):
403,
)
self.assertEqual(
self.client.get(reverse("panel:plan", args=[plan.pk])).status_code, 403
self.client.get(reverse("panel:plan", args=[plan.pk])).status_code,
403,
)
self.assertEqual(WebProvisioningPlan.objects.count(), 1)
def test_requesting_a_preview_requires_a_csrf_token(self):
browser = Client(enforce_csrf_checks=True)
browser.force_login(self.operator)
response = browser.post(reverse("panel:request_plan", args=[self.account.pk]))
response = browser.post(
reverse("panel:request_plan", args=[self.account.pk])
)
self.assertEqual(response.status_code, 403)
self.assertFalse(WebProvisioningPlan.objects.exists())
+49 -17
View File
@@ -53,10 +53,13 @@ class ResellerAccessTests(TestCase):
self.assertNotContains(accounts, self.bob_account.name)
self.assertNotContains(accounts, self.unassigned_account.name)
search = self.client.get(reverse("panel:accounts"), {"q": "bob.example"})
search = self.client.get(
reverse("panel:accounts"), {"q": "bob.example"}
)
self.assertContains(search, "No hosting accounts match this search.")
self.assertContains(
self.client.get(self.alice_account.get_absolute_url()), "alice.example"
self.client.get(self.alice_account.get_absolute_url()),
"alice.example",
)
for account in (self.bob_account, self.unassigned_account):
self.assertEqual(
@@ -66,11 +69,15 @@ class ResellerAccessTests(TestCase):
previews = self.client.get(reverse("panel:plans"))
self.assertContains(previews, "alice.example")
self.assertNotContains(previews, "bob.example")
preview = self.client.get(reverse("panel:plan", args=[self.alice_plan.pk]))
preview = self.client.get(
reverse("panel:plan", args=[self.alice_plan.pk])
)
self.assertContains(preview, "ServerName alice.example")
self.assertNotContains(preview, "Download deployment manifest")
self.assertEqual(
self.client.get(reverse("panel:plan", args=[self.bob_plan.pk])).status_code,
self.client.get(
reverse("panel:plan", args=[self.bob_plan.pk])
).status_code,
404,
)
@@ -80,7 +87,8 @@ class ResellerAccessTests(TestCase):
self.client.get(reverse("panel:accounts")), self.bob_account.name
)
self.assertEqual(
self.client.get(self.alice_account.get_absolute_url()).status_code, 404
self.client.get(self.alice_account.get_absolute_url()).status_code,
404,
)
for route, args in (
("panel:account_create", ()),
@@ -94,21 +102,29 @@ class ResellerAccessTests(TestCase):
):
with self.subTest(route=route):
self.assertEqual(
self.client.post(reverse(route, args=args)).status_code, 403
self.client.post(reverse(route, args=args)).status_code,
403,
)
self.assertEqual(
self.client.get(
reverse("panel:download_deployment_manifest", args=[self.bob_plan.pk])
reverse(
"panel:download_deployment_manifest",
args=[self.bob_plan.pk],
)
).status_code,
403,
)
self.assertRedirects(
self.client.get(reverse("admin:hosting_hostingaccount_changelist")),
self.client.get(
reverse("admin:hosting_hostingaccount_changelist")
),
reverse("admin:login") + "?next=/admin/hosting/hostingaccount/",
)
self.assertEqual(WebProvisioningPlan.objects.count(), 2)
def test_operator_assignment_takes_effect_on_the_next_reseller_request(self):
def test_operator_assignment_takes_effect_on_the_next_reseller_request(
self,
):
self.client.force_login(self.operator)
account = self.alice_account
response = self.client.post(
@@ -122,17 +138,25 @@ class ResellerAccessTests(TestCase):
)
self.assertRedirects(response, account.get_absolute_url())
self.assertContains(
self.client.get(account.get_absolute_url()), "<dd>bob</dd>", html=True
self.client.get(account.get_absolute_url()),
"<dd>bob</dd>",
html=True,
)
self.client.force_login(self.alice)
self.assertEqual(self.client.get(account.get_absolute_url()).status_code, 404)
self.assertEqual(
self.client.get(account.get_absolute_url()).status_code, 404
)
preview_url = reverse("panel:plan", args=[self.alice_plan.pk])
self.assertEqual(self.client.get(preview_url).status_code, 404)
self.client.force_login(self.bob)
self.assertContains(self.client.get(account.get_absolute_url()), account.name)
self.assertContains(self.client.get(preview_url), "ServerName alice.example")
self.assertContains(
self.client.get(account.get_absolute_url()), account.name
)
self.assertContains(
self.client.get(preview_url), "ServerName alice.example"
)
class ResellerAccountCreationTests(TestCase):
@@ -176,9 +200,13 @@ class ResellerAccountCreationTests(TestCase):
response = self.client.post(
self.create_url, payload | {"primary_domain": "overflow.example"}
)
self.assertContains(response, "Your hosting account limit has been reached.")
self.assertContains(
response, "Your hosting account limit has been reached."
)
self.assertFalse(
HostingAccount.objects.filter(primary_domain="overflow.example").exists()
HostingAccount.objects.filter(
primary_domain="overflow.example"
).exists()
)
def test_form_rejects_unavailable_or_missing_plan(self):
@@ -252,7 +280,11 @@ class ResellerAccountCreationTests(TestCase):
"hosting_plans": [self.unavailable.pk],
},
)
self.assertRedirects(response, reverse("admin:hosting_reseller_changelist"))
self.assertRedirects(
response, reverse("admin:hosting_reseller_changelist")
)
self.reseller.refresh_from_db()
self.assertEqual(self.reseller.account_limit, 6)
self.assertEqual(list(self.reseller.hosting_plans.all()), [self.unavailable])
self.assertEqual(
list(self.reseller.hosting_plans.all()), [self.unavailable]
)
+36 -10
View File
@@ -11,9 +11,18 @@ from django.utils import timezone
from coulobre.web_node import WebSite
from .models import HostingAccount, Reseller, WebActivation, WebProvisioningPlan
from .models import (
HostingAccount,
Reseller,
WebActivation,
WebProvisioningPlan,
)
from .node_client import activate_local_site
from .tasks import REDISPATCH_AFTER, activate_web_plan, dispatch_web_activations
from .tasks import (
REDISPATCH_AFTER,
activate_web_plan,
dispatch_web_activations,
)
@override_settings(LOCAL_WEB_ACTIVATION=True)
@@ -65,27 +74,38 @@ class WebActivationTests(TestCase):
activation.refresh_from_db()
self.assertEqual(activation.state, "configured")
def test_tenants_and_operators_without_activation_permission_are_denied(self):
def test_tenants_and_operators_without_activation_permission_are_denied(
self,
):
viewer = get_user_model().objects.create_user("viewer")
viewer.user_permissions.add(
*Permission.objects.filter(
codename__in=("view_hostingaccount", "view_webprovisioningplan")
codename__in=(
"view_hostingaccount",
"view_webprovisioningplan",
)
)
)
for user in (viewer, self.reseller_user):
with self.subTest(user=user):
self.client.force_login(user)
self.assertNotContains(self.client.get(self.detail), "Activate site")
self.assertNotContains(
self.client.get(self.detail), "Activate site"
)
self.assertEqual(self.client.post(self.url).status_code, 403)
self.assertFalse(WebActivation.objects.exists())
@override_settings(LOCAL_WEB_ACTIVATION=False)
def test_disabled_local_activation_keeps_manifest_downloads_available(self):
def test_disabled_local_activation_keeps_manifest_downloads_available(
self,
):
self.assertNotContains(self.client.get(self.detail), "Activate site")
self.assertEqual(self.client.post(self.url).status_code, 404)
self.assertEqual(
self.client.get(
reverse("panel:download_deployment_manifest", args=[self.plan.pk])
reverse(
"panel:download_deployment_manifest", args=[self.plan.pk]
)
).status_code,
200,
)
@@ -116,7 +136,9 @@ class WebActivationTests(TestCase):
activation = WebActivation.objects.create(
plan=self.plan, last_dispatched_at=timezone.now()
)
with patch("coulobre.hosting.tasks.activate_local_site", side_effect=OSError):
with patch(
"coulobre.hosting.tasks.activate_local_site", side_effect=OSError
):
activate_web_plan.run(activation.pk)
self.assertContains(self.client.get(self.detail), "Retry activation")
self.assertRedirects(self.client.post(self.url), self.detail)
@@ -132,7 +154,9 @@ class WebActivationTests(TestCase):
activate_web_plan.run(activation.pk)
apply.assert_not_called()
WebActivation.objects.filter(pk=activation.pk).update(
started_at=timezone.now() - REDISPATCH_AFTER - timedelta(seconds=1)
started_at=timezone.now()
- REDISPATCH_AFTER
- timedelta(seconds=1)
)
activate_web_plan.run(activation.pk)
apply.assert_called_once()
@@ -151,5 +175,7 @@ class WebActivationReplyTests(SimpleTestCase):
connection.makefile.return_value.__enter__.return_value = BytesIO(
json.dumps(reply).encode()
)
with self.assertRaisesMessage(ValueError, "invalid response for this site"):
with self.assertRaisesMessage(
ValueError, "invalid response for this site"
):
activate_local_site(site)
+20 -5
View File
@@ -26,12 +26,16 @@ class WebSmokeBundleTests(TestCase):
def setUp(self):
self.client.force_login(self.operator)
self.download = reverse("panel:download_smoke_bundle", args=[self.plan.pk])
self.download = reverse(
"panel:download_smoke_bundle", args=[self.plan.pk]
)
self.manifest = reverse(
"panel:download_deployment_manifest", args=[self.plan.pk]
)
def test_export_uses_the_reviewed_preview_and_matching_php_fpm_settings(self):
def test_export_uses_the_reviewed_preview_and_matching_php_fpm_settings(
self,
):
render_web_plan.run(self.plan.pk)
detail = self.client.get(reverse("panel:plan", args=[self.plan.pk]))
@@ -45,7 +49,12 @@ class WebSmokeBundleTests(TestCase):
with tarfile.open(fileobj=BytesIO(response.content)) as bundle:
self.assertEqual(
set(bundle.getnames()),
{"site.json", "apache.conf", "php-fpm.conf", "public/index.php"},
{
"site.json",
"apache.conf",
"php-fpm.conf",
"public/index.php",
},
)
config = json.load(bundle.extractfile("site.json"))
self.assertEqual(config["domain"], "example.org")
@@ -58,7 +67,9 @@ class WebSmokeBundleTests(TestCase):
self.assertIn(config["socket_path"], apache)
self.assertIn(f"listen = {config['socket_path']}", fpm)
self.assertIn(f"user = {config['service_user']}", fpm)
self.assertIn(b"<?php", bundle.extractfile("public/index.php").read())
self.assertIn(
b"<?php", bundle.extractfile("public/index.php").read()
)
def test_pending_and_stale_previews_cannot_be_exported(self):
self.assertEqual(self.client.get(self.download).status_code, 409)
@@ -91,7 +102,11 @@ class WebSmokeBundleTests(TestCase):
self.assertIn(".json", response["Content-Disposition"])
self.assertEqual(
response.json(),
{"version": 1, "account_id": self.account.pk, "domain": "example.org"},
{
"version": 1,
"account_id": self.account.pk,
"domain": "example.org",
},
)
self.plan.refresh_from_db()
+19 -6
View File
@@ -48,7 +48,9 @@ class WebNodeConfigurationTests(SimpleTestCase):
)
self.readiness.assert_called_once_with(self.socket)
def test_failed_apache_reload_rolls_back_files_and_reloads_previous_config(self):
def test_failed_apache_reload_rolls_back_files_and_reloads_previous_config(
self,
):
def fail_first_apache_reload(*command):
if (
command == ("/usr/sbin/service", "apache2", "reload")
@@ -81,11 +83,20 @@ class WebNodeStatusTests(SimpleTestCase):
self.state = Path(self.enterContext(TemporaryDirectory()))
self.site = WebSite(42, "example.org")
self.marker = self.state / "42.json"
self.enterContext(patch("coulobre.web_node_apply.STATE_DIRECTORY", self.state))
self.enterContext(patch("coulobre.web_node_apply.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)
patch("coulobre.web_node_apply.STATE_DIRECTORY", self.state)
)
self.enterContext(
patch("coulobre.web_node_apply.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.inspect = self.enterContext(
patch("coulobre.web_node_apply.check_installation")
@@ -114,7 +125,9 @@ class WebNodeStatusTests(SimpleTestCase):
},
)
def test_different_manifest_reports_a_conflict_without_inspecting_files(self):
def test_different_manifest_reports_a_conflict_without_inspecting_files(
self,
):
self.reserve(WebSite(42, "different.example"))
report = site_status(self.site)
+18 -6
View File
@@ -21,7 +21,9 @@ class WebSiteManifestTests(SimpleTestCase):
'DocumentRoot "/srv/coulobre/web/42/public"', site.render("apache")
)
self.assertIn('FilesMatch "\\.php$"', site.render("apache"))
self.assertIn("listen = /run/php/coulobre-42.sock", site.render("php-fpm"))
self.assertIn(
"listen = /run/php/coulobre-42.sock", site.render("php-fpm")
)
def test_manifest_rejects_wrong_versions_and_untrusted_configuration(self):
manifest = {"version": 1, "account_id": 42, "domain": "example.org"}
@@ -44,7 +46,9 @@ class WebSiteManifestTests(SimpleTestCase):
class WebActivationRequestTests(SimpleTestCase):
def setUp(self):
self.site = WebSite(42, "example.org")
self.apply = self.enterContext(patch("coulobre.web_node_apply.apply_site"))
self.apply = self.enterContext(
patch("coulobre.web_node_apply.apply_site")
)
def request(self, data):
output = StringIO()
@@ -60,7 +64,8 @@ class WebActivationRequestTests(SimpleTestCase):
self.apply.assert_called_once_with(self.site)
self.assertEqual(code, 0)
self.assertEqual(
reply, self.site.manifest() | {"state": "configured", "problem": None}
reply,
self.site.manifest() | {"state": "configured", "problem": None},
)
def test_rejects_invalid_or_oversized_input_before_apply(self):
@@ -69,7 +74,9 @@ class WebActivationRequestTests(SimpleTestCase):
b"\xff",
b"[" * MAX_REQUEST_BYTES,
b" " * (MAX_REQUEST_BYTES + 1),
json.dumps(self.site.manifest() | {"document_root": "/tmp"}).encode(),
json.dumps(
self.site.manifest() | {"document_root": "/tmp"}
).encode(),
):
with self.subTest(length=len(data)):
code, reply = self.request(data)
@@ -79,11 +86,16 @@ class WebActivationRequestTests(SimpleTestCase):
self.apply.assert_not_called()
def test_reports_node_failures_as_json_for_the_requested_site(self):
self.apply.side_effect = ValueError("The primary domain is already reserved.")
self.apply.side_effect = ValueError(
"The primary domain is already reserved."
)
code, reply = self.request(json.dumps(self.site.manifest()).encode())
self.assertEqual(code, 1)
self.assertEqual(
reply,
self.site.manifest()
| {"state": "failed", "problem": "The primary domain is already reserved."},
| {
"state": "failed",
"problem": "The primary domain is already reserved.",
},
)
+47 -13
View File
@@ -22,34 +22,66 @@ class DirectAdminWebRestoreTests(SimpleTestCase):
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.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.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)
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))
patch(
"coulobre.web_node_apply.check_installation",
return_value=(1001, 33),
)
)
self.owner = self.enterContext(
patch("coulobre.web_node_restore.os.chown")
)
self.owner = self.enterContext(patch("coulobre.web_node_restore.os.chown"))
entries = [
("backup/user.conf", b"username=client\ndomain=example.net\n", 0o600),
(
"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/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/example.net/public_html/logs/app.log",
b"private",
0o644,
),
("domains/other.example/public_html/index.php", b"other", 0o644),
]
tar = BytesIO()
@@ -124,7 +156,8 @@ class DirectAdminWebRestoreTests(SimpleTestCase):
with (
patch(
"coulobre.web_node_restore.copy_website", side_effect=write_to_live_root
"coulobre.web_node_restore.copy_website",
side_effect=write_to_live_root,
),
self.assertRaisesRegex(ValueError, "empty document root"),
):
@@ -149,7 +182,8 @@ class DirectAdminWebRestoreTests(SimpleTestCase):
def test_restore_checks_manifest_against_registered_site_first(self):
self.marker.write_text(
json.dumps(WebSite(42, "different.example").manifest()), encoding="utf-8"
json.dumps(WebSite(42, "different.example").manifest()),
encoding="utf-8",
)
with self.assertRaisesRegex(ValueError, "different manifest"):
+35 -11
View File
@@ -32,7 +32,8 @@ class HostingAccountAdminTests(TestCase):
self.assertContains(response, "Example hosting")
self.assertContains(response, "xn--bcher-kva.example")
self.assertEqual(
HostingAccount.objects.get().primary_domain, "xn--bcher-kva.example"
HostingAccount.objects.get().primary_domain,
"xn--bcher-kva.example",
)
list_url = reverse("admin:hosting_hostingaccount_changelist")
@@ -45,21 +46,31 @@ class HostingAccountAdminTests(TestCase):
)
response = self.client.post(
self.add_url,
{"name": "Duplicate account", "primary_domain": "XN--BCHER-KVA.Example."},
{
"name": "Duplicate account",
"primary_domain": "XN--BCHER-KVA.Example.",
},
)
form = response.context["adminform"].form
self.assertEqual(form.errors.as_data()["primary_domain"][0].code, "unique")
self.assertEqual(
form.errors.as_data()["primary_domain"][0].code, "unique"
)
self.assertEqual(HostingAccount.objects.count(), 1)
def test_invalid_domain_is_rejected(self):
response = self.client.post(
self.add_url,
{"name": "Invalid account", "primary_domain": "https://example.org"},
{
"name": "Invalid account",
"primary_domain": "https://example.org",
},
)
form = response.context["adminform"].form
self.assertEqual(form.errors.as_data()["primary_domain"][0].code, "invalid")
self.assertEqual(
form.errors.as_data()["primary_domain"][0].code, "invalid"
)
self.assertFalse(HostingAccount.objects.exists())
def test_staff_without_add_permission_cannot_register_an_account(self):
@@ -86,11 +97,16 @@ class WebProvisioningPlanTests(TestCase):
)
def test_admin_request_preserves_domain_until_worker_finishes(self):
self.client.force_login(get_user_model().objects.create_superuser("operator"))
self.client.force_login(
get_user_model().objects.create_superuser("operator")
)
list_url = reverse("admin:hosting_hostingaccount_changelist")
response = self.client.post(
list_url,
{"action": "request_web_plans", "_selected_action": [self.account.pk]},
{
"action": "request_web_plans",
"_selected_action": [self.account.pk],
},
)
self.assertRedirects(response, list_url)
@@ -105,17 +121,25 @@ class WebProvisioningPlanTests(TestCase):
self.assertIsNotNone(plan.completed_at)
self.assertIn("ServerName example.org", plan.apache_config)
self.assertIn(f"/srv/coulobre/web/{self.account.pk}/public", plan.apache_config)
self.assertIn(f"/run/php/coulobre-{self.account.pk}.sock", plan.apache_config)
self.assertIn(
f"/srv/coulobre/web/{self.account.pk}/public", plan.apache_config
)
self.assertIn(
f"/run/php/coulobre-{self.account.pk}.sock", plan.apache_config
)
plan_url = reverse("admin:hosting_webprovisioningplan_change", args=[plan.pk])
plan_url = reverse(
"admin:hosting_webprovisioningplan_change", args=[plan.pk]
)
response = self.client.get(plan_url)
self.assertContains(response, "<pre>&lt;VirtualHost")
self.assertContains(response, "ServerName example.org")
self.assertEqual(self.client.post(plan_url).status_code, 403)
@patch("coulobre.hosting.tasks.render_web_plan.apply_async")
def test_broker_failure_leaves_request_available_for_dispatch(self, publish):
def test_broker_failure_leaves_request_available_for_dispatch(
self, publish
):
plan = self.create_plan()
publish.side_effect = OperationalError("Broker unavailable")
with self.assertRaises(OperationalError):
+24 -6
View File
@@ -16,11 +16,21 @@ urlpatterns = [
name="login",
),
path("sign-out/", LogoutView.as_view(), name="logout"),
path("accounts/new/", views.AccountCreate.as_view(), name="account_create"),
path(
"accounts/new/", views.AccountCreate.as_view(), name="account_create"
),
path("accounts/<int:pk>/", views.AccountDetail.as_view(), name="account"),
path("accounts/<int:pk>/edit/", views.AccountEdit.as_view(), name="account_edit"),
path(
"accounts/<int:pk>/edit/",
views.AccountEdit.as_view(),
name="account_edit",
),
path("customers/", views.CustomerList.as_view(), name="customers"),
path("customers/new/", views.CustomerCreate.as_view(), name="customer_create"),
path(
"customers/new/",
views.CustomerCreate.as_view(),
name="customer_create",
),
path(
"customers/<int:pk>/access/",
views.CustomerAccess.as_view(),
@@ -46,7 +56,11 @@ urlpatterns = [
views.DnsZoneCreate.as_view(),
name="dns_zone_create",
),
path("dns-zones/<int:pk>/edit/", views.DnsZoneEdit.as_view(), name="dns_zone_edit"),
path(
"dns-zones/<int:pk>/edit/",
views.DnsZoneEdit.as_view(),
name="dns_zone_edit",
),
path(
"dns-zones/<int:pk>/manifest/",
views.DownloadDnsZoneManifest.as_view(),
@@ -73,9 +87,13 @@ urlpatterns = [
name="mailbox_provision",
),
path(
"accounts/<int:pk>/plans/", views.RequestWebPlan.as_view(), name="request_plan"
"accounts/<int:pk>/plans/",
views.RequestWebPlan.as_view(),
name="request_plan",
),
path(
"hosting-plans/", views.HostingPlanList.as_view(), name="hosting_plans"
),
path("hosting-plans/", views.HostingPlanList.as_view(), name="hosting_plans"),
path(
"hosting-plans/new/",
views.HostingPlanCreate.as_view(),
+135 -46
View File
@@ -5,14 +5,25 @@ from django.contrib.auth.mixins import PermissionRequiredMixin
from django.core.exceptions import ValidationError
from django.db import IntegrityError, transaction
from django.db.models import Q
from django.http import Http404, HttpResponse, HttpResponseBadRequest, JsonResponse
from django.http import (
Http404,
HttpResponse,
HttpResponseBadRequest,
JsonResponse,
)
from django.shortcuts import get_object_or_404, redirect
from django.urls import reverse, reverse_lazy
from django.utils.decorators import method_decorator
from django.utils.functional import cached_property
from django.views import View
from django.views.decorators.debug import sensitive_post_parameters
from django.views.generic import CreateView, DetailView, FormView, ListView, UpdateView
from django.views.generic import (
CreateView,
DetailView,
FormView,
ListView,
UpdateView,
)
from django.views.generic.detail import SingleObjectMixin
from coulobre.dns_node import MAX_SOA_SERIAL
@@ -54,9 +65,17 @@ VIEW_DATABASES = "hosting.view_hostingdatabase"
VIEW_DNS_ZONES = "hosting.view_hostingdnszone"
VIEW_MAILBOXES = "hosting.view_hostingmailbox"
ACTIVATE_WEB = (VIEW_ACCOUNTS, VIEW_PLANS, "hosting.add_webactivation")
PROVISION_DATABASE = (VIEW_ACCOUNTS, VIEW_DATABASES, "hosting.add_databaseprovisioning")
PROVISION_DATABASE = (
VIEW_ACCOUNTS,
VIEW_DATABASES,
"hosting.add_databaseprovisioning",
)
PUBLISH_DNS = (VIEW_ACCOUNTS, VIEW_DNS_ZONES, "hosting.add_dnspublication")
PROVISION_MAILBOX = (VIEW_ACCOUNTS, VIEW_MAILBOXES, "hosting.add_mailboxprovisioning")
PROVISION_MAILBOX = (
VIEW_ACCOUNTS,
VIEW_MAILBOXES,
"hosting.add_mailboxprovisioning",
)
class AccountList(TenantScopeMixin, PermissionRequiredMixin, ListView):
@@ -97,7 +116,9 @@ class AccountEditor:
def get_form_class(self):
self.fields = ("name", "primary_domain")
reseller = reseller_for_user(self.request.user)
if reseller is not None or self.request.user.has_perm(VIEW_HOSTING_PLANS):
if reseller is not None or self.request.user.has_perm(
VIEW_HOSTING_PLANS
):
self.fields += ("hosting_plan",)
if reseller is None and self.request.user.has_perm(VIEW_RESELLERS):
self.fields += ("reseller",)
@@ -120,15 +141,18 @@ class AccountEditor:
if name in form.fields:
field = form.fields[name]
field.empty_label = "Unassigned"
field.queryset = field.queryset.select_related("user").order_by(
"user__username"
)
field.queryset = field.queryset.select_related(
"user"
).order_by("user__username")
return form
class AccountCreate(PermissionRequiredMixin, AccountEditor, CreateView):
permission_required = (VIEW_ACCOUNTS, "hosting.add_hostingaccount")
extra_context = {"page_title": "Add hosting account", "submit_label": "Add account"}
extra_context = {
"page_title": "Add hosting account",
"submit_label": "Add account",
}
def has_permission(self):
if customer_for_user(self.request.user) is not None:
@@ -190,7 +214,9 @@ class AccountDetail(TenantScopeMixin, PermissionRequiredMixin, DetailView):
reseller = reseller_for_user(user)
customer = customer_for_user(user)
tenant = reseller is not None or customer is not None
if reseller is not None or (customer is None and user.has_perm(VIEW_PLANS)):
if reseller is not None or (
customer is None and user.has_perm(VIEW_PLANS)
):
context["plans"] = self.object.webprovisioningplan_set.order_by(
"-requested_at", "-pk"
)[:10]
@@ -199,7 +225,9 @@ class AccountDetail(TenantScopeMixin, PermissionRequiredMixin, DetailView):
if not tenant and user.has_perms(PROVISION_DATABASE):
databases = databases.select_related("provisioning")
context["manage_database_provisioning"] = True
context["local_database_enabled"] = settings.LOCAL_DATABASE_PROVISIONING
context["local_database_enabled"] = (
settings.LOCAL_DATABASE_PROVISIONING
)
context["databases"] = databases
if tenant or user.has_perm(VIEW_DNS_ZONES):
zone_list = self.object.dns_zones.all()
@@ -221,15 +249,17 @@ class AccountDetail(TenantScopeMixin, PermissionRequiredMixin, DetailView):
if not tenant and user.has_perms(PROVISION_MAILBOX):
mailboxes = mailboxes.select_related("provisioning")
context["manage_mailbox_provisioning"] = True
context["local_mailbox_enabled"] = settings.LOCAL_MAILBOX_PROVISIONING
context["local_mailbox_enabled"] = (
settings.LOCAL_MAILBOX_PROVISIONING
)
context["mailboxes"] = mailboxes
return context
class CustomerList(OperatorOnlyMixin, PermissionRequiredMixin, ListView):
queryset = Customer.objects.select_related("user__hosting_reseller").order_by(
"user__username"
)
queryset = Customer.objects.select_related(
"user__hosting_reseller"
).order_by("user__username")
permission_required = VIEW_CUSTOMERS
template_name = "hosting/customer_list.html"
context_object_name = "customers"
@@ -246,7 +276,9 @@ class CustomerList(OperatorOnlyMixin, PermissionRequiredMixin, ListView):
return super().get_context_data(search=self.search, **kwargs)
@method_decorator(sensitive_post_parameters("password1", "password2"), name="dispatch")
@method_decorator(
sensitive_post_parameters("password1", "password2"), name="dispatch"
)
class CustomerCreate(OperatorOnlyMixin, PermissionRequiredMixin, FormView):
permission_required = (VIEW_CUSTOMERS, "hosting.add_customer")
form_class = UserCreationForm
@@ -282,7 +314,9 @@ class CustomerAccess(OperatorOnlyMixin, PermissionRequiredMixin, View):
resellers = Reseller.objects.values("user_id")
users = (
get_user_model()
.objects.filter(pk__in=customer, is_staff=False, is_superuser=False)
.objects.filter(
pk__in=customer, is_staff=False, is_superuser=False
)
.exclude(pk__in=resellers)
)
if not users.update(is_active=access == "restore"):
@@ -297,7 +331,8 @@ class ResourceRequestCreate(PermissionRequiredMixin, CreateView):
def has_permission(self):
return self.customer is not None or (
reseller_for_user(self.request.user) is None and super().has_permission()
reseller_for_user(self.request.user) is None
and super().has_permission()
)
@cached_property
@@ -315,7 +350,9 @@ class ResourceRequestCreate(PermissionRequiredMixin, CreateView):
self.object = self.create_request(
self.account.pk,
**form.cleaned_data,
customer_id=self.customer.pk if self.customer is not None else None,
customer_id=self.customer.pk
if self.customer is not None
else None,
)
except HostingAccount.DoesNotExist as error:
raise Http404 from error
@@ -329,11 +366,17 @@ class DatabaseCreate(ResourceRequestCreate):
model = HostingDatabase
fields = ("suffix",)
template_name = "hosting/database_form.html"
permission_required = (VIEW_ACCOUNTS, VIEW_DATABASES, "hosting.add_hostingdatabase")
permission_required = (
VIEW_ACCOUNTS,
VIEW_DATABASES,
"hosting.add_hostingdatabase",
)
create_request = staticmethod(create_database_request)
class DownloadDatabaseManifest(OperatorOnlyMixin, PermissionRequiredMixin, View):
class DownloadDatabaseManifest(
OperatorOnlyMixin, PermissionRequiredMixin, View
):
permission_required = (VIEW_ACCOUNTS, VIEW_DATABASES)
def get(self, request, pk):
@@ -342,12 +385,17 @@ class DownloadDatabaseManifest(OperatorOnlyMixin, PermissionRequiredMixin, View)
database.spec.manifest(),
headers={
"Cache-Control": "private, no-store",
"Content-Disposition": f'attachment; filename="coulobre-database-{database.pk}.json"',
"Content-Disposition": (
"attachment; "
f'filename="coulobre-database-{database.pk}.json"'
),
},
)
class RequestDatabaseProvisioning(OperatorOnlyMixin, PermissionRequiredMixin, View):
class RequestDatabaseProvisioning(
OperatorOnlyMixin, PermissionRequiredMixin, View
):
permission_required = PROVISION_DATABASE
def post(self, request, pk):
@@ -377,7 +425,11 @@ class DnsZoneEditor(OperatorOnlyMixin, PermissionRequiredMixin, FormView):
class DnsZoneCreate(DnsZoneEditor):
form_class = DnsZoneForm
permission_required = (VIEW_ACCOUNTS, VIEW_DNS_ZONES, "hosting.add_hostingdnszone")
permission_required = (
VIEW_ACCOUNTS,
VIEW_DNS_ZONES,
"hosting.add_hostingdnszone",
)
extra_context = {"page_title": "Add DNS zone"}
@cached_property
@@ -395,7 +447,9 @@ class DnsZoneCreate(DnsZoneEditor):
try:
with transaction.atomic():
HostingDnsZone.objects.create(
account=self.account, domain=self.domain, **form.cleaned_data
account=self.account,
domain=self.domain,
**form.cleaned_data,
)
except IntegrityError:
if not HostingDnsZone.objects.filter(domain=self.domain).exists():
@@ -417,7 +471,8 @@ class DnsZoneEdit(DnsZoneEditor):
@cached_property
def zone(self):
return get_object_or_404(
HostingDnsZone.objects.select_related("account"), pk=self.kwargs["pk"]
HostingDnsZone.objects.select_related("account"),
pk=self.kwargs["pk"],
)
@property
@@ -449,23 +504,29 @@ class DnsZoneEdit(DnsZoneEditor):
def form_valid(self, form):
values = form.cleaned_data
serial = values["serial"]
if all(getattr(self.zone, field) == value for field, value in values.items()):
if all(
getattr(self.zone, field) == value
for field, value in values.items()
):
return super().form_valid(form)
next_serial = (serial + 1) % (MAX_SOA_SERIAL + 1)
updated = HostingDnsZone.objects.filter(pk=self.zone.pk, serial=serial).update(
**(values | {"serial": next_serial})
)
updated = HostingDnsZone.objects.filter(
pk=self.zone.pk, serial=serial
).update(**(values | {"serial": next_serial}))
if not updated:
form.add_error(
None,
"This DNS zone changed while you were editing it. Reopen the form and try again.",
"This DNS zone changed while you were editing it. "
"Reopen the form and try again.",
)
return self.form_invalid(form)
return super().form_valid(form)
class DownloadDnsZoneManifest(OperatorOnlyMixin, PermissionRequiredMixin, View):
class DownloadDnsZoneManifest(
OperatorOnlyMixin, PermissionRequiredMixin, View
):
permission_required = (VIEW_ACCOUNTS, VIEW_DNS_ZONES)
def get(self, request, pk):
@@ -474,7 +535,9 @@ class DownloadDnsZoneManifest(OperatorOnlyMixin, PermissionRequiredMixin, View):
zone.spec.manifest(),
headers={
"Cache-Control": "private, no-store",
"Content-Disposition": f'attachment; filename="coulobre-zone-{zone.pk}.json"',
"Content-Disposition": (
f'attachment; filename="coulobre-zone-{zone.pk}.json"'
),
},
)
@@ -490,7 +553,9 @@ class RequestDnsPublication(OperatorOnlyMixin, PermissionRequiredMixin, View):
except HostingDnsZone.DoesNotExist as error:
raise Http404 from error
except ValueError as error:
return HttpResponse(str(error), status=409, content_type="text/plain")
return HttpResponse(
str(error), status=409, content_type="text/plain"
)
return redirect(zone.account)
@@ -498,7 +563,11 @@ class MailboxCreate(ResourceRequestCreate):
model = HostingMailbox
fields = ("local_part",)
template_name = "hosting/mailbox_form.html"
permission_required = (VIEW_ACCOUNTS, VIEW_MAILBOXES, "hosting.add_hostingmailbox")
permission_required = (
VIEW_ACCOUNTS,
VIEW_MAILBOXES,
"hosting.add_hostingmailbox",
)
create_request = staticmethod(create_mailbox_request)
def get_form(self, form_class=None):
@@ -507,7 +576,9 @@ class MailboxCreate(ResourceRequestCreate):
return form
class DownloadMailboxManifest(OperatorOnlyMixin, PermissionRequiredMixin, View):
class DownloadMailboxManifest(
OperatorOnlyMixin, PermissionRequiredMixin, View
):
permission_required = (VIEW_ACCOUNTS, VIEW_MAILBOXES)
def get(self, request, pk):
@@ -518,19 +589,25 @@ class DownloadMailboxManifest(OperatorOnlyMixin, PermissionRequiredMixin, View):
mailbox.spec.manifest(),
headers={
"Cache-Control": "private, no-store",
"Content-Disposition": f'attachment; filename="coulobre-mailbox-{mailbox.pk}.json"',
"Content-Disposition": (
"attachment; "
f'filename="coulobre-mailbox-{mailbox.pk}.json"'
),
},
)
class RequestMailboxProvisioning(OperatorOnlyMixin, PermissionRequiredMixin, View):
class RequestMailboxProvisioning(
OperatorOnlyMixin, PermissionRequiredMixin, View
):
permission_required = PROVISION_MAILBOX
def post(self, request, pk):
if not settings.LOCAL_MAILBOX_PROVISIONING:
raise Http404
mailbox = get_object_or_404(
HostingMailbox.objects.select_related("mail_domain__account"), pk=pk
HostingMailbox.objects.select_related("mail_domain__account"),
pk=pk,
)
MailboxProvisioning.objects.queue(mailbox=mailbox)
return redirect(mailbox.mail_domain.account)
@@ -555,14 +632,20 @@ class HostingPlanCreate(
OperatorOnlyMixin, PermissionRequiredMixin, HostingPlanEditor, CreateView
):
permission_required = (VIEW_HOSTING_PLANS, "hosting.add_hostingplan")
extra_context = {"page_title": "Add hosting plan", "submit_label": "Add plan"}
extra_context = {
"page_title": "Add hosting plan",
"submit_label": "Add plan",
}
class HostingPlanEdit(
OperatorOnlyMixin, PermissionRequiredMixin, HostingPlanEditor, UpdateView
):
permission_required = (VIEW_HOSTING_PLANS, "hosting.change_hostingplan")
extra_context = {"page_title": "Edit hosting plan", "submit_label": "Save changes"}
extra_context = {
"page_title": "Edit hosting plan",
"submit_label": "Save changes",
}
def form_valid(self, form):
self.object = form.save(commit=False)
@@ -594,7 +677,9 @@ class PlanList(TenantScopeMixin, PermissionRequiredMixin, ListView):
class PlanDetail(TenantScopeMixin, PermissionRequiredMixin, DetailView):
queryset = WebProvisioningPlan.objects.select_related("account", "activation")
queryset = WebProvisioningPlan.objects.select_related(
"account", "activation"
)
permission_required = VIEW_PLANS
reseller_relation = "account__reseller"
template_name = "hosting/plan_detail.html"
@@ -603,7 +688,8 @@ class PlanDetail(TenantScopeMixin, PermissionRequiredMixin, DetailView):
def get_context_data(self, **kwargs):
user = self.request.user
return super().get_context_data(
manage_activation=not is_tenant(user) and user.has_perms(ACTIVATE_WEB),
manage_activation=not is_tenant(user)
and user.has_perms(ACTIVATE_WEB),
local_activation_enabled=settings.LOCAL_WEB_ACTIVATION,
**kwargs,
)
@@ -621,7 +707,8 @@ class RequestWebActivation(
plan = self.get_object()
if not plan.can_export:
return HttpResponse(
"Request a completed Apache preview for the current account domain.",
"Request a completed Apache preview for the current "
"account domain.",
status=409,
content_type="text/plain",
)
@@ -636,7 +723,8 @@ class DownloadWebPlan(OperatorOnlyMixin, PlanDetail):
plan = self.object
if not plan.can_export:
return HttpResponse(
"Request a completed Apache preview for the current account domain.",
"Request a completed Apache preview for the current "
"account domain.",
status=409,
content_type="text/plain",
)
@@ -655,7 +743,8 @@ class DownloadWebPlan(OperatorOnlyMixin, PlanDetail):
headers={
"Cache-Control": "private, no-store",
"Content-Disposition": (
f'attachment; filename="coulobre-web-plan-{plan.pk}.{extension}"'
"attachment; "
f'filename="coulobre-web-plan-{plan.pk}.{extension}"'
),
},
)
+20 -6
View File
@@ -25,18 +25,25 @@ class MailboxSpec:
if not isinstance(self.domain, str):
raise ValueError("Enter a valid mail domain.")
object.__setattr__(self, "domain", canonical_domain(self.domain))
if not isinstance(self.local_part, str) or not self.local_part.isascii():
if (
not isinstance(self.local_part, str)
or not self.local_part.isascii()
):
raise ValueError(INVALID_LOCAL_PART)
local_part = self.local_part.lower()
if (
len(local_part) > LOCAL_PART_MAX_LENGTH
or not re.fullmatch(r"[a-z0-9](?:[a-z0-9._-]*[a-z0-9])?", local_part)
or not re.fullmatch(
r"[a-z0-9](?:[a-z0-9._-]*[a-z0-9])?", local_part
)
or ".." in local_part
):
raise ValueError(INVALID_LOCAL_PART)
object.__setattr__(self, "local_part", local_part)
if len(self.address) > 254:
raise ValueError("The full mailbox address must be at most 254 characters.")
raise ValueError(
"The full mailbox address must be at most 254 characters."
)
@property
def address(self):
@@ -59,7 +66,10 @@ class MailboxSpec:
"local_part",
}:
raise ValueError("Expected a virtual mailbox manifest.")
if type(data["version"]) is not int or data["version"] != MANIFEST_VERSION:
if (
type(data["version"]) is not int
or data["version"] != MANIFEST_VERSION
):
raise ValueError("Unsupported mailbox manifest version.")
if data["kind"] != MANIFEST_KIND:
raise ValueError("Expected a virtual mailbox manifest.")
@@ -69,7 +79,9 @@ class MailboxSpec:
def main(argv=None):
parser = argparse.ArgumentParser(prog="coulobre-mail-node")
commands = parser.add_subparsers(dest="command", required=True)
inspect = commands.add_parser("inspect", help="Inspect a virtual mailbox manifest.")
inspect = commands.add_parser(
"inspect", help="Inspect a virtual mailbox manifest."
)
inspect.add_argument("manifest", type=Path)
apply = commands.add_parser(
"apply", help="Install a virtual mailbox on the mail node."
@@ -79,7 +91,9 @@ def main(argv=None):
"apply-request",
help="Apply one mailbox manifest from standard input and report JSON.",
)
status = commands.add_parser("status", help="Check an installed virtual mailbox.")
status = commands.add_parser(
"status", help="Check an installed virtual mailbox."
)
status.add_argument("manifest", type=Path)
args = parser.parse_args(argv)
+75 -25
View File
@@ -27,7 +27,8 @@ LMTP_SOCKET = Path("/var/spool/postfix/private/dovecot-lmtp")
MANAGED_HEADER = "# Managed by Coulobre Panel\n"
PASSWORD = re.compile(r"[A-Za-z0-9_-]{43}")
PASSWORD_HASH = re.compile(
r"\{SHA512-CRYPT\}\$6\$(?:rounds=[0-9]+\$)?[./0-9A-Za-z]{1,16}\$[./0-9A-Za-z]{86}"
r"\{SHA512-CRYPT\}\$6\$(?:rounds=[0-9]+\$)?"
r"[./0-9A-Za-z]{1,16}\$[./0-9A-Za-z]{86}"
)
@@ -55,7 +56,9 @@ class Credentials:
"password": self.password,
"password_hash": self.password_hash,
}
write_new_file(self.path, json.dumps(document, indent=2) + "\n", mode=0o600)
write_new_file(
self.path, json.dumps(document, indent=2) + "\n", mode=0o600
)
def credential_path(mailbox):
@@ -82,7 +85,9 @@ def load_credentials(path):
):
raise ValueError
except (KeyError, TypeError, ValueError):
raise ValueError(f"Invalid mailbox credentials record at {path}.") from None
raise ValueError(
f"Invalid mailbox credentials record at {path}."
) from None
return record
@@ -100,7 +105,9 @@ def apply_mailbox(mailbox):
@contextmanager
def locked_state(*, create):
try:
require_root_directory(STATE_DIRECTORY, create_mode=0o700 if create else None)
require_root_directory(
STATE_DIRECTORY, create_mode=0o700 if create else None
)
directory = os.open(
STATE_DIRECTORY, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW
)
@@ -143,7 +150,9 @@ def check_mailbox(mailbox):
or dovecot_home(mailbox) is not None
or postfix_lookup(mailbox.address, POSTFIX_MAILBOXES) is not None
):
raise ValueError("The mailbox has resources outside Coulobre's registry.")
raise ValueError(
"The mailbox has resources outside Coulobre's registry."
)
return "not_installed"
record = load_credentials(path)
@@ -159,12 +168,16 @@ def check_mailbox(mailbox):
if not contents.startswith(MANAGED_HEADER) or not rows.issubset(
contents.removeprefix(MANAGED_HEADER).splitlines()
):
raise ValueError(f"The managed mailbox entry is missing from {table}.")
raise ValueError(
f"The managed mailbox entry is missing from {table}."
)
if (
postfix_lookup(mailbox.domain, POSTFIX_DOMAINS) != "1"
or postfix_lookup(mailbox.address, POSTFIX_MAILBOXES) != "1"
):
raise ValueError("Postfix did not resolve the managed domain and recipient.")
raise ValueError(
"Postfix did not resolve the managed domain and recipient."
)
if dovecot_home(mailbox) != str(home):
raise ValueError("Dovecot did not resolve the managed mailbox home.")
try:
@@ -187,17 +200,25 @@ def check_mailbox(mailbox):
def install_mailbox(mailbox, state_directory):
account, auth_group = check_services(mailbox)
records = [
load_credentials(path) for path in sorted(STATE_DIRECTORY.glob("*.json"))
load_credentials(path)
for path in sorted(STATE_DIRECTORY.glob("*.json"))
]
active = next((record for record in records if record.mailbox == mailbox), None)
active = next(
(record for record in records if record.mailbox == mailbox), None
)
prepared = [record for record in records if home_is_prepared(record)]
previous = lookup_tables(prepared, account, auth_group)
ready = {path: check_lookup_table(path, table) for path, table in previous.items()}
ready = {
path: check_lookup_table(path, table)
for path, table in previous.items()
}
home = mailbox_home(mailbox)
ensure_mail_directory(home.parent)
if active is None:
if os.path.lexists(home) or dovecot_home(mailbox) is not None:
raise ValueError("The mailbox already exists outside Coulobre's registry.")
raise ValueError(
"The mailbox already exists outside Coulobre's registry."
)
password = secrets.token_urlsafe(32)
password_hash = run(
"doveadm",
@@ -207,7 +228,9 @@ def install_mailbox(mailbox, state_directory):
standard_input=f"{password}\n{password}\n",
)
if not PASSWORD_HASH.fullmatch(password_hash):
raise ValueError("Dovecot did not return the expected password hash.")
raise ValueError(
"Dovecot did not return the expected password hash."
)
active = Credentials(mailbox, password, password_hash)
active.save()
os.fsync(state_directory)
@@ -257,7 +280,9 @@ def read_lookup_table(path, mode, group):
return ""
contents = read_root_file(path, mode=mode)
if group is not None and path.lstat().st_gid != group:
raise ValueError(f"Expected ownership by the Dovecot auth group for {path}.")
raise ValueError(
f"Expected ownership by the Dovecot auth group for {path}."
)
return contents
@@ -268,7 +293,9 @@ def check_lookup_table(path, table):
not contents.startswith(MANAGED_HEADER)
or set(contents.removeprefix(MANAGED_HEADER).splitlines()) - rows
):
raise ValueError(f"Existing entries in {path} differ from Coulobre's registry.")
raise ValueError(
f"Existing entries in {path} differ from Coulobre's registry."
)
return contents
@@ -286,7 +313,10 @@ def publish_table(path, table, previous):
def home_is_prepared(record):
if not os.path.lexists(record.home_marker):
return False
if read_root_file(record.home_marker, mode=0o600) != f"{record.mailbox.address}\n":
if (
read_root_file(record.home_marker, mode=0o600)
!= f"{record.mailbox.address}\n"
):
raise ValueError(
"The mailbox home marker conflicts with its credentials record."
)
@@ -316,7 +346,9 @@ def ensure_mail_home(home, account, *, create):
if create and info.st_uid == 0 and not any(home.iterdir()):
os.chown(home, account.pw_uid, account.pw_gid, follow_symlinks=False)
elif (info.st_uid, info.st_gid) != (account.pw_uid, account.pw_gid):
raise ValueError(f"Unexpected ownership for the mailbox directory at {home}.")
raise ValueError(
f"Unexpected ownership for the mailbox directory at {home}."
)
def check_services(mailbox):
@@ -343,17 +375,25 @@ def check_services(mailbox):
}
for name, expected in settings.items():
if run("postconf", "-hx", name) != expected:
raise ValueError(f"Configure Postfix {name} for Coulobre mailboxes.")
raise ValueError(
f"Configure Postfix {name} for Coulobre mailboxes."
)
local_domains = run("postconf", "-hx", "mydestination")
if mailbox.domain in re.split(r"[\s,]+", local_domains.lower()):
raise ValueError("The requested mail domain is a local Postfix destination.")
raise ValueError(
"The requested mail domain is a local Postfix destination."
)
check_dovecot_maildir()
first_uid = int(run("doveconf", "-h", "first_valid_uid"))
last_uid = int(run("doveconf", "-h", "last_valid_uid"))
if account.pw_uid < first_uid or (last_uid and account.pw_uid > last_uid):
raise ValueError(f"Allow the {MAIL_USER} UID in Dovecot's valid UID range.")
raise ValueError(
f"Allow the {MAIL_USER} UID in Dovecot's valid UID range."
)
if not LMTP_SOCKET.is_socket():
raise ValueError(f"Dovecot is missing its LMTP socket at {LMTP_SOCKET}.")
raise ValueError(
f"Dovecot is missing its LMTP socket at {LMTP_SOCKET}."
)
run("postfix", "status")
try:
auth_group = grp.getgrnam("dovecot").gr_gid
@@ -372,14 +412,19 @@ def check_dovecot_maildir():
or run("doveconf", "-h", "mail_path") != "~/Maildir"
):
raise ValueError(
"Configure Dovecot mail_driver and mail_path for the managed Maildir."
"Configure Dovecot mail_driver and mail_path for the "
"managed Maildir."
)
elif run("doveconf", "-h", "mail_location") != "maildir:~/Maildir":
raise ValueError("Configure Dovecot mail_location for the managed Maildir.")
raise ValueError(
"Configure Dovecot mail_location for the managed Maildir."
)
def dovecot_home(mailbox):
return run("doveadm", "user", "-f", "home", mailbox.address, missing_exit=67)
return run(
"doveadm", "user", "-f", "home", mailbox.address, missing_exit=67
)
def postfix_lookup(key, path):
@@ -420,8 +465,13 @@ def run(*command, standard_input=None, missing_exit=None, missing_output=None):
raise ValueError(f"{name} timed out.") from None
if result.returncode:
message = result.stderr.strip() or result.stdout.strip()
if result.returncode == missing_exit and missing_output in (None, message):
if result.returncode == missing_exit and missing_output in (
None,
message,
):
return None
details = message if standard_input is None else ""
raise ValueError(f"{name} failed ({result.returncode}). {details}".rstrip())
raise ValueError(
f"{name} failed ({result.returncode}). {details}".rstrip()
)
return result.stdout.strip()
+13 -3
View File
@@ -13,13 +13,21 @@ def require_root_directory(path, *, create_mode=None):
def check_root_directory(path):
info = path.lstat()
if not stat.S_ISDIR(info.st_mode) or info.st_uid != 0 or info.st_mode & 0o022:
if (
not stat.S_ISDIR(info.st_mode)
or info.st_uid != 0
or info.st_mode & 0o022
):
raise ValueError(f"Expected a root-controlled directory at {path}.")
def read_root_file(path, *, mode=None):
info = path.lstat()
if not stat.S_ISREG(info.st_mode) or info.st_uid != 0 or info.st_mode & 0o022:
if (
not stat.S_ISREG(info.st_mode)
or info.st_uid != 0
or info.st_mode & 0o022
):
raise ValueError(f"Expected a root-controlled file at {path}.")
if mode is not None and stat.S_IMODE(info.st_mode) != mode:
raise ValueError(f"Expected permissions {mode:04o} on {path}.")
@@ -27,7 +35,9 @@ def read_root_file(path, *, mode=None):
def write_new_file(path, content, *, mode, group=None):
with NamedTemporaryFile(mode="w", encoding="utf-8", dir=path.parent) as staged:
with NamedTemporaryFile(
mode="w", encoding="utf-8", dir=path.parent
) as staged:
staged.write(content)
staged.flush()
if group is not None:
+6 -1
View File
@@ -5,7 +5,12 @@ MAX_REQUEST_BYTES = 4096
def serve_apply_request(
manifest_version, parse_manifest, apply, *, limit=MAX_REQUEST_BYTES, identity=None
manifest_version,
parse_manifest,
apply,
*,
limit=MAX_REQUEST_BYTES,
identity=None,
):
report = {"version": manifest_version}
try:
+14 -3
View File
@@ -84,11 +84,22 @@ else:
AUTH_PASSWORD_VALIDATORS = [
{
"NAME": "django.contrib.auth.password_validation.UserAttributeSimilarityValidator"
"NAME": (
"django.contrib.auth.password_validation."
"UserAttributeSimilarityValidator"
)
},
{"NAME": "django.contrib.auth.password_validation.MinimumLengthValidator"},
{"NAME": "django.contrib.auth.password_validation.CommonPasswordValidator"},
{"NAME": "django.contrib.auth.password_validation.NumericPasswordValidator"},
{
"NAME": (
"django.contrib.auth.password_validation.CommonPasswordValidator"
)
},
{
"NAME": (
"django.contrib.auth.password_validation.NumericPasswordValidator"
)
},
]
TIME_ZONE = "UTC"
+22 -7
View File
@@ -11,7 +11,10 @@ from .domain_names import canonical_domain
from .node_requests import serve_apply_request
MANIFEST_VERSION = 1
CONFIGURATIONS = {"apache": "apache-vhost.conf", "php-fpm": "php-fpm-pool.conf"}
CONFIGURATIONS = {
"apache": "apache-vhost.conf",
"php-fpm": "php-fpm-pool.conf",
}
@dataclass(frozen=True)
@@ -20,8 +23,13 @@ class WebSite:
domain: str
def __post_init__(self):
if type(self.account_id) is not int or not 1 <= self.account_id <= 2**63 - 1:
raise ValueError("The account ID must be a positive 64-bit integer.")
if (
type(self.account_id) is not int
or not 1 <= self.account_id <= 2**63 - 1
):
raise ValueError(
"The account ID must be a positive 64-bit integer."
)
if not isinstance(self.domain, str):
raise ValueError("The domain must be a string.")
object.__setattr__(self, "domain", canonical_domain(self.domain))
@@ -75,7 +83,9 @@ def main(argv=None):
)
render.add_argument("manifest", type=Path)
render.add_argument("configuration", choices=CONFIGURATIONS)
apply = commands.add_parser("apply", help="Install a site on an Ubuntu web node.")
apply = commands.add_parser(
"apply", help="Install a site on an Ubuntu web node."
)
apply.add_argument("manifest", type=Path)
commands.add_parser(
"apply-request",
@@ -91,13 +101,17 @@ def main(argv=None):
)
restore.add_argument("manifest", type=Path)
restore.add_argument("backup", type=Path)
restore.add_argument("--source-root", choices=DOCUMENT_ROOTS, default="public_html")
restore.add_argument(
"--source-root", choices=DOCUMENT_ROOTS, default="public_html"
)
args = parser.parse_args(argv)
if args.command == "apply-request":
from .web_node_apply import apply_site
return serve_apply_request(MANIFEST_VERSION, WebSite.from_manifest, apply_site)
return serve_apply_request(
MANIFEST_VERSION, WebSite.from_manifest, apply_site
)
try:
payload = json.loads(args.manifest.read_text(encoding="utf-8"))
@@ -118,7 +132,8 @@ def main(argv=None):
print(
json.dumps(
restore_website(site, args.backup, args.source_root), indent=2
restore_website(site, args.backup, args.source_root),
indent=2,
)
)
else:
+31 -8
View File
@@ -60,13 +60,21 @@ def apply_site(site):
def install_site(site):
user = site.configuration()["service_user"]
paths = SitePaths.for_site(site)
owned_paths = (paths.account, paths.apache, paths.enabled, paths.pool, paths.socket)
owned_paths = (
paths.account,
paths.apache,
paths.enabled,
paths.pool,
paths.socket,
)
check_services()
reserve_account(site, user, owned_paths)
uid, web_gid = ensure_system_account(user, paths.account)
require_root_directory(paths.account, create_mode=0o755)
ensure_public_directory(paths.account / "public", uid, web_gid)
install_configurations(site, paths.apache, paths.enabled, paths.pool, paths.socket)
install_configurations(
site, paths.apache, paths.enabled, paths.pool, paths.socket
)
def site_status(site):
@@ -88,7 +96,11 @@ def site_status(site):
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": "needs_attention",
"problem": str(error),
}
return {**report, "state": "configured"}
@@ -118,10 +130,14 @@ def check_installation(site, paths):
check_public_directory(paths.account / "public", uid, gid)
check_configuration(paths.apache, site.render("apache"))
check_configuration(paths.pool, site.render("php-fpm"))
check_site_link(paths.enabled, Path("../sites-available") / paths.apache.name)
check_site_link(
paths.enabled, Path("../sites-available") / paths.apache.name
)
check_services()
if not socket_exists(paths.socket):
raise ValueError(f"PHP-FPM is missing the site socket at {paths.socket}.")
raise ValueError(
f"PHP-FPM is missing the site socket at {paths.socket}."
)
return uid, gid
@@ -140,7 +156,8 @@ def reserve_account(site, user, paths):
if existing == marker:
if saved != manifest:
raise ValueError(
"The account is already reserved with a different manifest."
"The account is already reserved with a different "
"manifest."
)
elif saved["domain"] == site.domain:
raise ValueError(
@@ -180,7 +197,9 @@ def ensure_system_account(user, account_dir):
group = current_group(user)
if group is not None:
if group.gr_mem or not group.gr_gid:
raise ValueError(f"Unexpected members or ID in the {user} group.")
raise ValueError(
f"Unexpected members or ID in the {user} group."
)
group_options = ("--gid", str(group.gr_gid))
run(
"/usr/sbin/useradd",
@@ -221,7 +240,11 @@ def ensure_public_directory(path, uid, gid):
if not os.path.lexists(path):
path.mkdir(mode=0o700)
info = path.lstat()
if stat.S_ISDIR(info.st_mode) and info.st_uid == 0 and not any(path.iterdir()):
if (
stat.S_ISDIR(info.st_mode)
and info.st_uid == 0
and not any(path.iterdir())
):
path.chmod(0o750)
os.chown(path, uid, gid, follow_symlinks=False)
check_public_directory(path, uid, gid)
+18 -6
View File
@@ -35,16 +35,22 @@ def restore_website(site, backup, source_root):
private.add(target)
summary = copy_website(
backup, site.domain, source_root, staged, on_copy=remember_private_entry
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.
# 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
raise ValueError(
"Restore requires an empty document root."
) from None
return {
**site.manifest(),
@@ -57,14 +63,20 @@ def restore_website(site, backup, source_root):
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 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(".")
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(".")
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)