import json import socket from importlib.metadata import version from django.views.decorators.debug import sensitive_variables from coulobre.account_backup_request import ( BACKUP_SOCKET, BACKUP_TIMEOUT_SECONDS, ) from coulobre.account_restore_request import ( RESTORE_SOCKET, RESTORE_TIMEOUT_SECONDS, ) from coulobre.linked_updates import ROLES, UNIT_DIR, read_probe from coulobre.mail_dns import dkim_key, normalize_rsa_dkim_record from coulobre.mail_node import MailboxQuotaUpdate, MailboxSigningRequest from coulobre.node_probe import PROBE_BYTES, parse_status_probe from coulobre.php_pool_settings import PhpPoolSettings from coulobre.php_runtime import validate_php_version from coulobre.web_node import ( MAX_STORAGE_BYTES, WebActivationRequest, WebAliasRequest, WebPhpRequest, WebPhpVersionRequest, WebQuotaRequest, WebStorageRequest, ) RESPONSE_LIMIT = 32768 class NodeReplyError(ValueError): pass def activate_local_site( site, php_settings, allowed_versions, *, starter_page=False ): reply = apply_on_local_node( WebActivationRequest( site, php_settings, allowed_versions, starter_page ), "/run/coulobre-web-apply.sock", "web node", "website activation", ) try: version = reply.get("applied_php_version") validate_php_version(version) options = PhpPoolSettings.from_manifest( reply.get("applied_php_settings") ) except ValueError: raise NodeReplyError( "The web node returned invalid PHP configuration." ) from None return options, version def update_local_php_version(site, version): reply = apply_on_local_node( WebPhpVersionRequest(site, version), "/run/coulobre-web-apply.sock", "web node", "PHP version change", ) if reply.get("applied_php_version") != version: raise NodeReplyError("The web node reported a different PHP series.") return version def update_local_php_settings(site, php_settings): reply = apply_on_local_node( WebPhpRequest(site, php_settings, "set_php_settings"), "/run/coulobre-web-apply.sock", "web node", "PHP pool settings", ) try: applied = PhpPoolSettings.from_manifest( reply.get("applied_php_settings") ) except ValueError: raise ValueError( "The web node returned invalid PHP pool settings." ) from None if applied != php_settings: raise ValueError("The web node reported different PHP pool settings.") return applied def measure_local_site_storage(site): reply = apply_on_local_node( WebStorageRequest(site), "/run/coulobre-web-apply.sock", "web node", "website storage measurement", ) used_bytes = reply.get("used_bytes") if type(used_bytes) is not int or not 0 <= used_bytes <= MAX_STORAGE_BYTES: raise ValueError( "The web node returned an invalid storage measurement." ) return used_bytes def set_local_site_storage_limit(site, limit_mib): apply_on_local_node( WebQuotaRequest(site, limit_mib), "/run/coulobre-web-apply.sock", "web node", "website storage limit", ) def enable_local_https(site): apply_on_local_node( site, "/run/coulobre-https-apply.sock", "web node", "HTTPS request" ) def update_local_website_alias(alias, operation): apply_on_local_node( WebAliasRequest(alias, operation), "/run/coulobre-web-apply.sock", "web node", "website alias", ) def update_local_sftp(keys): apply_on_local_node( keys, "/run/coulobre-sftp-apply.sock", "web node", "SFTP key request", identity=keys.identity(), ) def provision_local_database(database): apply_on_local_node( database, "/run/coulobre-database-apply.sock", "MariaDB node", "database", ) def publish_local_zone(zone): apply_on_local_node( zone, "/run/coulobre-dns-apply.sock", "BIND9 node", "zone", identity=zone.manifest_identity(), ) def provision_local_mailbox(mailbox): apply_on_local_node( mailbox, "/run/coulobre-mail-apply.sock", "mail node", "mailbox" ) def provision_signing_mailbox(mailbox): reply = apply_on_local_node( MailboxSigningRequest(mailbox), "/run/coulobre-mail-apply.sock", "mail node", "mailbox and signing key", ) public = reply.get("dkim") if ( not isinstance(public, str) or len(public) > 1024 or not public.startswith("v=DKIM1; k=rsa; p=") or dkim_key(public)[0] != "ok" ): raise ValueError("The mail node returned an invalid DKIM public key.") return normalize_rsa_dkim_record(public) def update_local_mailbox_quota(mailbox): apply_on_local_node( MailboxQuotaUpdate(mailbox), "/run/coulobre-mail-apply.sock", "mail node", "mailbox quota update", ) def create_local_account_backup(request): reply = apply_on_local_node( request, BACKUP_SOCKET, "backup node", "account backup", identity=request.identity(), timeout=BACKUP_TIMEOUT_SECONDS + 15, ) size = reply.get("archive_bytes") if size is not None and (type(size) is not int or not 0 < size < 2**63): raise ValueError("The backup node returned an invalid archive size.") return size def expire_local_account_backup(request): reply = apply_on_local_node( request, BACKUP_SOCKET, "backup node", "account archive expiration", identity=request.identity(), timeout=BACKUP_TIMEOUT_SECONDS + 15, ) removed, reason = reply.get("removed"), reply.get("reason") if removed is True and reason is None: return None if removed is False and isinstance(reason, str) and reason.strip(): return reason.strip()[:2000] raise ValueError("The backup node returned an invalid expiration result.") def restore_local_website(request): apply_on_local_node( request, RESTORE_SOCKET, "backup node", "website restore", timeout=RESTORE_TIMEOUT_SECONDS + 15, ) def restore_local_component(request): apply_on_local_node( request, RESTORE_SOCKET, "backup node", "component restore", timeout=RESTORE_TIMEOUT_SECONDS + 15, ) def encode_manifest(manifest): return json.dumps(manifest).encode("utf-8") @sensitive_variables("body", "reply") def apply_on_local_node( spec, socket_path, node, resource, *, identity=None, timeout=195 ): require_matching_receiver(socket_path) manifest = spec.manifest() expected = manifest if identity is None else identity with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as client: client.settimeout(timeout) client.connect(socket_path) client.sendall(encode_manifest(manifest)) client.shutdown(socket.SHUT_WR) with client.makefile("rb") as response: body = response.read(RESPONSE_LIMIT + 1) if len(body) > RESPONSE_LIMIT: raise NodeReplyError(f"The {node} returned an oversized response.") if not body: raise NodeReplyError( f"The {node} closed the connection without a response." ) 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"] matches = all( type(reply.get(key)) is type(value) and reply[key] == value for key, value in expected.items() ) except (KeyError, TypeError, ValueError, RecursionError): raise NodeReplyError(invalid_response) from None if matches: if state == "configured" and problem is None: return reply if state == "failed" and isinstance(problem, str) and problem.strip(): raise ValueError(problem.strip()[:2000]) raise NodeReplyError(invalid_response) def require_matching_receiver(socket_path): for role in ROLES: unit = f"coulobre-{role}-apply" if str(socket_path) != f"/run/{unit}.sock": continue if not (UNIT_DIR / f"{unit}@.service.d/remote.conf").exists(): return try: report = parse_status_probe(read_probe(role, PROBE_BYTES), role) if report["state"] == "configured" and report[ "release" ] == version("coulobre-panel"): return except (OSError, ValueError): pass raise NodeReplyError( f"The linked {role} receiver is not ready for this release." )