diff --git a/pyproject.toml b/pyproject.toml index 4238663..d47b317 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -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 diff --git a/src/coulobre/database_node.py b/src/coulobre/database_node.py index 61a6462..323554c 100644 --- a/src/coulobre/database_node.py +++ b/src/coulobre/database_node.py @@ -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") diff --git a/src/coulobre/database_node_apply.py b/src/coulobre/database_node_apply.py index 05c3f0b..7a281fa 100644 --- a/src/coulobre/database_node_apply.py +++ b/src/coulobre/database_node_apply.py @@ -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}`.*" diff --git a/src/coulobre/directadmin.py b/src/coulobre/directadmin.py index fa8e481..c62e55a 100644 --- a/src/coulobre/directadmin.py +++ b/src/coulobre/directadmin.py @@ -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) diff --git a/src/coulobre/directadmin_website.py b/src/coulobre/directadmin_website.py index 3d9539e..914f248 100644 --- a/src/coulobre/directadmin_website.py +++ b/src/coulobre/directadmin_website.py @@ -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." diff --git a/src/coulobre/dns_node.py b/src/coulobre/dns_node.py index 506dc9f..3b0191a 100644 --- a/src/coulobre/dns_node.py +++ b/src/coulobre/dns_node.py @@ -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: diff --git a/src/coulobre/dns_node_apply.py b/src/coulobre/dns_node_apply.py index 2dc1956..903a63e 100644 --- a/src/coulobre/dns_node_apply.py +++ b/src/coulobre/dns_node_apply.py @@ -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() diff --git a/src/coulobre/domain_names.py b/src/coulobre/domain_names.py index 3d122d8..504ccb0 100644 --- a/src/coulobre/domain_names.py +++ b/src/coulobre/domain_names.py @@ -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: diff --git a/src/coulobre/hosting/access.py b/src/coulobre/hosting/access.py index 3145f11..f07e5e0 100644 --- a/src/coulobre/hosting/access.py +++ b/src/coulobre/hosting/access.py @@ -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 diff --git a/src/coulobre/hosting/admin.py b/src/coulobre/hosting/admin.py index e85e797..f7ed25e 100644 --- a/src/coulobre/hosting/admin.py +++ b/src/coulobre/hosting/admin.py @@ -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 = ( diff --git a/src/coulobre/hosting/directadmin_import.py b/src/coulobre/hosting/directadmin_import.py index b989d92..2ffce1e 100644 --- a/src/coulobre/hosting/directadmin_import.py +++ b/src/coulobre/hosting/directadmin_import.py @@ -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": [], diff --git a/src/coulobre/hosting/dns_forms.py b/src/coulobre/hosting/dns_forms.py index 64b3c9c..72a1098 100644 --- a/src/coulobre/hosting/dns_forms.py +++ b/src/coulobre/hosting/dns_forms.py @@ -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: diff --git a/src/coulobre/hosting/dns_publication.py b/src/coulobre/hosting/dns_publication.py index c4e0028..3b17126 100644 --- a/src/coulobre/hosting/dns_publication.py +++ b/src/coulobre/hosting/dns_publication.py @@ -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 diff --git a/src/coulobre/hosting/fields.py b/src/coulobre/hosting/fields.py index 7c144c8..b2c068a 100644 --- a/src/coulobre/hosting/fields.py +++ b/src/coulobre/hosting/fields.py @@ -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 diff --git a/src/coulobre/hosting/management/commands/import_directadmin.py b/src/coulobre/hosting/management/commands/import_directadmin.py index a835bf3..2a8dd09 100644 --- a/src/coulobre/hosting/management/commands/import_directadmin.py +++ b/src/coulobre/hosting/management/commands/import_directadmin.py @@ -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( diff --git a/src/coulobre/hosting/management/commands/plan_directadmin_import.py b/src/coulobre/hosting/management/commands/plan_directadmin_import.py index eea13ec..9b8cf03 100644 --- a/src/coulobre/hosting/management/commands/plan_directadmin_import.py +++ b/src/coulobre/hosting/management/commands/plan_directadmin_import.py @@ -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)) diff --git a/src/coulobre/hosting/migrations/0002_webprovisioningplan.py b/src/coulobre/hosting/migrations/0002_webprovisioningplan.py index f2b218a..7c15a5d 100644 --- a/src/coulobre/hosting/migrations/0002_webprovisioningplan.py +++ b/src/coulobre/hosting/migrations/0002_webprovisioningplan.py @@ -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)), ( diff --git a/src/coulobre/hosting/migrations/0006_hostingdatabase.py b/src/coulobre/hosting/migrations/0006_hostingdatabase.py index d630161..c87e02d 100644 --- a/src/coulobre/hosting/migrations/0006_hostingdatabase.py +++ b/src/coulobre/hosting/migrations/0006_hostingdatabase.py @@ -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", diff --git a/src/coulobre/hosting/migrations/0012_hosting_plan_quotas.py b/src/coulobre/hosting/migrations/0012_hosting_plan_quotas.py index f23b1c7..70e953c 100644 --- a/src/coulobre/hosting/migrations/0012_hosting_plan_quotas.py +++ b/src/coulobre/hosting/migrations/0012_hosting_plan_quotas.py @@ -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, ), ), diff --git a/src/coulobre/hosting/migrations/0013_web_activation.py b/src/coulobre/hosting/migrations/0013_web_activation.py index 41613f3..b7fa67f 100644 --- a/src/coulobre/hosting/migrations/0013_web_activation.py +++ b/src/coulobre/hosting/migrations/0013_web_activation.py @@ -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)), diff --git a/src/coulobre/hosting/migrations/0014_database_provisioning.py b/src/coulobre/hosting/migrations/0014_database_provisioning.py index 69c0ea3..7a7f965 100644 --- a/src/coulobre/hosting/migrations/0014_database_provisioning.py +++ b/src/coulobre/hosting/migrations/0014_database_provisioning.py @@ -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)), diff --git a/src/coulobre/hosting/migrations/0015_dns_publication.py b/src/coulobre/hosting/migrations/0015_dns_publication.py index ae4a0f5..e9048bb 100644 --- a/src/coulobre/hosting/migrations/0015_dns_publication.py +++ b/src/coulobre/hosting/migrations/0015_dns_publication.py @@ -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)), diff --git a/src/coulobre/hosting/migrations/0016_mailbox_provisioning.py b/src/coulobre/hosting/migrations/0016_mailbox_provisioning.py index 820ee73..6268485 100644 --- a/src/coulobre/hosting/migrations/0016_mailbox_provisioning.py +++ b/src/coulobre/hosting/migrations/0016_mailbox_provisioning.py @@ -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)), diff --git a/src/coulobre/hosting/models.py b/src/coulobre/hosting/models.py index 30bdd75..30ca7a3 100644 --- a/src/coulobre/hosting/models.py +++ b/src/coulobre/hosting/models.py @@ -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", ) diff --git a/src/coulobre/hosting/node_client.py b/src/coulobre/hosting/node_client.py index 096ce86..b4a2e4e 100644 --- a/src/coulobre/hosting/node_client.py +++ b/src/coulobre/hosting/node_client.py @@ -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"] diff --git a/src/coulobre/hosting/reseller_accounts.py b/src/coulobre/hosting/reseller_accounts.py index f685312..9669012 100644 --- a/src/coulobre/hosting/reseller_accounts.py +++ b/src/coulobre/hosting/reseller_accounts.py @@ -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 diff --git a/src/coulobre/hosting/resource_requests.py b/src/coulobre/hosting/resource_requests.py index b29f83e..33884b3 100644 --- a/src/coulobre/hosting/resource_requests.py +++ b/src/coulobre/hosting/resource_requests.py @@ -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) diff --git a/src/coulobre/hosting/tasks.py b/src/coulobre/hosting/tasks.py index 040599d..d61d12b 100644 --- a/src/coulobre/hosting/tasks.py +++ b/src/coulobre/hosting/tasks.py @@ -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 diff --git a/src/coulobre/hosting/test_customers.py b/src/coulobre/hosting/test_customers.py index 7ff9e96..d5937cc 100644 --- a/src/coulobre/hosting/test_customers.py +++ b/src/coulobre/hosting/test_customers.py @@ -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) diff --git a/src/coulobre/hosting/test_database_node_apply.py b/src/coulobre/hosting/test_database_node_apply.py index 8171a1f..ecf89f6 100644 --- a/src/coulobre/hosting/test_database_node_apply.py +++ b/src/coulobre/hosting/test_database_node_apply.py @@ -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) diff --git a/src/coulobre/hosting/test_database_provisioning.py b/src/coulobre/hosting/test_database_provisioning.py index 9ac4856..cf7c82a 100644 --- a/src/coulobre/hosting/test_database_provisioning.py +++ b/src/coulobre/hosting/test_database_provisioning.py @@ -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) diff --git a/src/coulobre/hosting/test_databases.py b/src/coulobre/hosting/test_databases.py index 07b9b11..bbf8b9d 100644 --- a/src/coulobre/hosting/test_databases.py +++ b/src/coulobre/hosting/test_databases.py @@ -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() diff --git a/src/coulobre/hosting/test_directadmin.py b/src/coulobre/hosting/test_directadmin.py index 0758566..94dc061 100644 --- a/src/coulobre/hosting/test_directadmin.py +++ b/src/coulobre/hosting/test_directadmin.py @@ -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( diff --git a/src/coulobre/hosting/test_directadmin_import.py b/src/coulobre/hosting/test_directadmin_import.py index 4a783ec..e0c1fcc 100644 --- a/src/coulobre/hosting/test_directadmin_import.py +++ b/src/coulobre/hosting/test_directadmin_import.py @@ -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) diff --git a/src/coulobre/hosting/test_directadmin_website.py b/src/coulobre/hosting/test_directadmin_website.py index b12e1a2..3e0407c 100644 --- a/src/coulobre/hosting/test_directadmin_website.py +++ b/src/coulobre/hosting/test_directadmin_website.py @@ -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, diff --git a/src/coulobre/hosting/test_dns_node.py b/src/coulobre/hosting/test_dns_node.py index f7ef92f..671eb9e 100644 --- a/src/coulobre/hosting/test_dns_node.py +++ b/src/coulobre/hosting/test_dns_node.py @@ -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": [], diff --git a/src/coulobre/hosting/test_dns_node_apply.py b/src/coulobre/hosting/test_dns_node_apply.py index cfae036..9d3906e 100644 --- a/src/coulobre/hosting/test_dns_node_apply.py +++ b/src/coulobre/hosting/test_dns_node_apply.py @@ -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"): diff --git a/src/coulobre/hosting/test_dns_publication.py b/src/coulobre/hosting/test_dns_publication.py index 5952688..79b48cd 100644 --- a/src/coulobre/hosting/test_dns_publication.py +++ b/src/coulobre/hosting/test_dns_publication.py @@ -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) diff --git a/src/coulobre/hosting/test_dns_zones.py b/src/coulobre/hosting/test_dns_zones.py index 3b6c8c4..0419594 100644 --- a/src/coulobre/hosting/test_dns_zones.py +++ b/src/coulobre/hosting/test_dns_zones.py @@ -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) diff --git a/src/coulobre/hosting/test_hosting_plans.py b/src/coulobre/hosting/test_hosting_plans.py index 80ea446..7ba51c8 100644 --- a/src/coulobre/hosting/test_hosting_plans.py +++ b/src/coulobre/hosting/test_hosting_plans.py @@ -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() diff --git a/src/coulobre/hosting/test_mail_node_apply.py b/src/coulobre/hosting/test_mail_node_apply.py index ae363aa..9f3e001 100644 --- a/src/coulobre/hosting/test_mail_node_apply.py +++ b/src/coulobre/hosting/test_mail_node_apply.py @@ -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="") diff --git a/src/coulobre/hosting/test_mailbox_provisioning.py b/src/coulobre/hosting/test_mailbox_provisioning.py index b5ae0c7..f749b0d 100644 --- a/src/coulobre/hosting/test_mailbox_provisioning.py +++ b/src/coulobre/hosting/test_mailbox_provisioning.py @@ -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) diff --git a/src/coulobre/hosting/test_mailboxes.py b/src/coulobre/hosting/test_mailboxes.py index 2dd2915..c0ed21e 100644 --- a/src/coulobre/hosting/test_mailboxes.py +++ b/src/coulobre/hosting/test_mailboxes.py @@ -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}, diff --git a/src/coulobre/hosting/test_panel.py b/src/coulobre/hosting/test_panel.py index c041404..7a7501e 100644 --- a/src/coulobre/hosting/test_panel.py +++ b/src/coulobre/hosting/test_panel.py @@ -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()) diff --git a/src/coulobre/hosting/test_resellers.py b/src/coulobre/hosting/test_resellers.py index 0952322..646dbeb 100644 --- a/src/coulobre/hosting/test_resellers.py +++ b/src/coulobre/hosting/test_resellers.py @@ -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()), "