diff --git a/docs/deployment.md b/docs/deployment.md index fa2bc0b..ddb5e27 100644 --- a/docs/deployment.md +++ b/docs/deployment.md @@ -3491,6 +3491,27 @@ other panel as well. If a panel secret changes, exchange its new public key and re-enroll it. Each panel keeps its own hosting accounts and can operate while another panel is unreachable. +#### View hosting accounts across panels + +On each owning panel, open **Enrolled panels**, select **Hosting inventory +sharing** on the source panel's row, and choose **Share hosting accounts**. +Only the mapped local operator can enable sharing. This grants read-only +access to active account names, primary domains and status, not to +customer profiles or service credentials. Sharing is directional and off +by default, including for previously enrolled peers. + +On the source panel, open **Hosting accounts → All nodes** to search and +filter by the owning panel. The combined view shows the first page from +each node. Select a node to page through all of its results. The node +column uses short hostnames unless they collide. Hover or focus the node +label to read the full host shown by the enrollment. Account links open +the owning panel, which still checks its own operator sign-in. + +If a peer is unavailable, doesn't share its inventory or hasn't been +upgraded to a version that supports it, the list marks the results as +incomplete. **This node** continues to show the regular local list. The +cluster inventory is not exposed to customers or managers. + ### Set up hosting features Open **About Coulobre → Configure features** as a superuser with a verified diff --git a/src/coulobre/hosting/cluster_account_views.py b/src/coulobre/hosting/cluster_account_views.py new file mode 100644 index 0000000..9147fec --- /dev/null +++ b/src/coulobre/hosting/cluster_account_views.py @@ -0,0 +1,62 @@ +from django.http import Http404 +from django.utils.decorators import method_decorator +from django.views.decorators.cache import never_cache +from django.views.generic import TemplateView + +from .account_administration import OperatorAuthorization +from .cluster_accounts import ( + MAX_OFFSET, + PAGE_SIZE, + collect_inventory, + inventory_nodes, + search_term, +) + + +@method_decorator(never_cache, name="dispatch") +class ClusterAccountList(OperatorAuthorization, TemplateView): + template_name = "hosting/cluster_account_list.html" + + def get_context_data(self, **kwargs): + nodes = inventory_nodes(self.request) + if not nodes: + raise Http404 + selected = self.request.GET.get("node", "") + subset = [ + node for node in nodes if not selected or node.key == selected + ] + if not subset: + raise Http404 + offset = self.request.GET.get("offset", "0") + if ( + not offset.isascii() + or not offset.isdecimal() + or len(offset) > len(str(MAX_OFFSET)) + or int(offset) > MAX_OFFSET + or int(offset) % PAGE_SIZE + or (int(offset) and not selected) + ): + raise Http404 + offset = int(offset) + try: + search = search_term(self.request.GET.get("q", "")) + except ValueError: + raise Http404 from None + pages = collect_inventory(subset, self.request.user, search, offset) + return super().get_context_data( + cluster_view=True, + cluster_nodes=nodes, + pages=pages, + unavailable_nodes=[ + page["node"] for page in pages if page["unavailable"] + ], + selected_node=selected, + search=search, + previous_offset=offset - PAGE_SIZE if offset else None, + next_offset=( + offset + PAGE_SIZE + if selected and pages[0]["more"] and offset < MAX_OFFSET + else None + ), + **kwargs, + ) diff --git a/src/coulobre/hosting/cluster_accounts.py b/src/coulobre/hosting/cluster_accounts.py new file mode 100644 index 0000000..fe6a26f --- /dev/null +++ b/src/coulobre/hosting/cluster_accounts.py @@ -0,0 +1,225 @@ +"""Read-only account summaries exchanged by enrolled Core panels.""" + +import json +from concurrent.futures import ThreadPoolExecutor +from dataclasses import dataclass, replace +from ipaddress import ip_address +from urllib.parse import urlsplit + +from django.conf import settings +from django.db.models import Q +from django.urls import reverse + +from coulobre.domain_names import canonical_domain + +from .access import PanelRole +from .models import HostingAccount, PanelPeer +from .peering import ( + MAPPED_OPERATOR_REQUIRED, + MAX_PEERS, + PeerAccessError, + peer_call, +) + +PAGE_SIZE = 20 +MAX_OFFSET = 1_000_000 + + +@dataclass(frozen=True) +class HostingNode: + key: str + authority: str + label: str + peer: PanelPeer | None = None + + +def node_authority(origin): + parts = urlsplit(origin) + return parts.netloc, parts.hostname or parts.netloc + + +def node_label(host): + try: + ip_address(host) + except ValueError: + return host.split(".", 1)[0] + return host + + +def unambiguous_label(authority, host, group): + if len(group) < 2: + return node_label(host) + if group.count(host) > 1: + return authority + labels = host.split(".") + for length in range(2, len(labels) + 1): + prefix = labels[:length] + if all( + part == host or part.split(".")[:length] != prefix + for part in group + ): + return ".".join(prefix) + return authority + + +def inventory_nodes(request): + user = request.user + if not ( + settings.PASSWORD_RESET_ORIGIN + and user.is_active + and user.is_superuser + and user.is_verified() + and getattr(request, "active_panel_role", None) == PanelRole.ADMIN + and not getattr(request, "impersonation", None) + ): + return [] + peers = list( + PanelPeer.objects.filter(operator=user, revoked_at__isnull=True)[ + :MAX_PEERS + ] + ) + if not peers: + return [] + origins = [("local", settings.PASSWORD_RESET_ORIGIN, None)] + origins.extend((str(peer.pk), peer.origin, peer) for peer in peers) + nodes = [] + hosts = [] + for key, origin, peer in origins: + authority, host = node_authority(origin) + nodes.append(HostingNode(key, authority, node_label(host), peer)) + hosts.append(host) + return [ + replace( + node, + label=unambiguous_label( + node.authority, + host, + [other for other in hosts if node_label(other) == node.label], + ), + ) + for node, host in zip(nodes, hosts, strict=True) + ] + + +def search_term(value): + search = value.strip()[:253] + if search and not search.isprintable(): + raise ValueError("The account search contains invalid characters.") + return search + + +def account_slice(search, offset): + accounts = HostingAccount.objects.filter(retired_at__isnull=True).order_by( + "primary_domain", "pk" + ) + if search: + accounts = accounts.filter( + Q(name__icontains=search) | Q(primary_domain__icontains=search) + ) + rows = list( + accounts.values("id", "name", "primary_domain", "services_suspended")[ + offset : offset + PAGE_SIZE + 1 + ] + ) + return {"accounts": rows[:PAGE_SIZE], "more": len(rows) > PAGE_SIZE} + + +def peer_account_slice(peer, actor, value): + if not ( + peer.account_inventory_allowed + and peer.operator.is_active + and peer.operator.is_superuser + and actor == peer.remote_username + ): + raise PeerAccessError(MAPPED_OPERATOR_REQUIRED) + try: + query = json.loads(value) + if ( + not isinstance(query, dict) + or set(query) != {"q", "offset"} + or not isinstance(query["q"], str) + or len(query["q"]) > 253 + or type(query["offset"]) is not int + or not 0 <= query["offset"] <= MAX_OFFSET + ): + raise ValueError + search = search_term(query["q"]) + except (ValueError, RecursionError): + raise PeerAccessError( + "The account inventory request is invalid." + ) from None + return account_slice(search, query["offset"]) + + +def validate_slice(result): + if ( + set(result) != {"accounts", "more"} + or type(result["more"]) is not bool + or not isinstance(result["accounts"], list) + or len(result["accounts"]) > PAGE_SIZE + or (result["more"] and len(result["accounts"]) != PAGE_SIZE) + ): + raise ValueError + seen = set() + for account in result["accounts"]: + if ( + not isinstance(account, dict) + or set(account) + != {"id", "name", "primary_domain", "services_suspended"} + or type(account["id"]) is not int + or not 1 <= account["id"] <= 2**63 - 1 + or account["id"] in seen + or not isinstance(account["name"], str) + or len(account["name"]) > 120 + or not isinstance(account["primary_domain"], str) + or canonical_domain(account["primary_domain"]) + != account["primary_domain"] + or type(account["services_suspended"]) is not bool + ): + raise ValueError + seen.add(account["id"]) + return result + + +def fetch_slice(peer, actor, query): + try: + return validate_slice( + peer_call(peer, "account-inventory", actor, query) + ) + except (ValueError, TimeoutError): + return None + + +def collect_inventory(nodes, user, search, offset): + remote = [node for node in nodes if node.peer] + query = json.dumps({"q": search, "offset": offset}, ensure_ascii=False) + responses = {} + if remote: + with ThreadPoolExecutor(max_workers=len(remote)) as pool: + jobs = { + node.key: pool.submit( + fetch_slice, node.peer, user.get_username(), query + ) + for node in remote + } + responses = {key: job.result() for key, job in jobs.items()} + pages = [] + for node in nodes: + result = ( + responses[node.key] if node.peer else account_slice(search, offset) + ) + accounts = [] + if result is not None: + prefix = node.peer.origin if node.peer else "" + for row in result["accounts"]: + path = reverse("panel:account", kwargs={"pk": row["id"]}) + accounts.append(row | {"url": prefix + path}) + pages.append( + { + "node": node, + "accounts": accounts, + "more": bool(result and result["more"]), + "unavailable": result is None, + } + ) + return pages diff --git a/src/coulobre/hosting/migrations/0091_panel_peer_account_inventory.py b/src/coulobre/hosting/migrations/0091_panel_peer_account_inventory.py new file mode 100644 index 0000000..0a87f2c --- /dev/null +++ b/src/coulobre/hosting/migrations/0091_panel_peer_account_inventory.py @@ -0,0 +1,17 @@ +# Generated by Django 5.2.19 on 2026-12-03 10:56 + +from django.db import migrations, models + + +class Migration(migrations.Migration): + dependencies = [ + ("hosting", "0090_mail_domain_alias"), + ] + + operations = [ + migrations.AddField( + model_name="panelpeer", + name="account_inventory_allowed", + field=models.BooleanField(default=False), + ), + ] diff --git a/src/coulobre/hosting/models.py b/src/coulobre/hosting/models.py index 51d3088..bde7460 100644 --- a/src/coulobre/hosting/models.py +++ b/src/coulobre/hosting/models.py @@ -975,6 +975,7 @@ class PanelPeer(models.Model): enrolled_at = models.DateTimeField(default=timezone.now) revoked_at = models.DateTimeField(null=True) checked_at = models.DateTimeField(null=True) + account_inventory_allowed = models.BooleanField(default=False) status = models.JSONField(default=dict) problem = models.CharField(max_length=160, blank=True) diff --git a/src/coulobre/hosting/peer_views.py b/src/coulobre/hosting/peer_views.py index 84d9df7..30dee83 100644 --- a/src/coulobre/hosting/peer_views.py +++ b/src/coulobre/hosting/peer_views.py @@ -20,6 +20,7 @@ from django.views.generic import FormView from .account_administration import OperatorAuthorization from .account_security import AuthorizedSecurityChange, confirmed_device +from .cluster_accounts import peer_account_slice from .models import PanelPeer, PeerAction, PeerActionGrant from .peering import ( MAX_PACKET, @@ -60,6 +61,10 @@ def peer_endpoint(request): match message["action"]: case "status": result = local_status() + case "account-inventory": + result = peer_account_slice( + peer, message["actor"], message["value"] + ) case "package-check": result = queue_package_check( peer, message["actor"], message["value"] @@ -165,10 +170,27 @@ class PeerManagementView(OperatorAuthorization, FormView): raise PermissionDenied PanelPeer.objects.filter( pk=peer.pk, revoked_at__isnull=True - ).update(revoked_at=timezone.now(), status={}, problem="") + ).update( + revoked_at=timezone.now(), + status={}, + problem="", + account_inventory_allowed=False, + ) messages.success(request, "Peer access revoked.") elif action == "refresh": refresh_peer(peer) + elif action in ("allow-inventory", "deny-inventory"): + self.require_mapped_operator(peer) + allowed = action == "allow-inventory" + PanelPeer.objects.filter( + pk=peer.pk, revoked_at__isnull=True, operator=request.user + ).update(account_inventory_allowed=allowed) + messages.success( + request, + "Hosting account inventory sharing enabled." + if allowed + else "Hosting account inventory sharing disabled.", + ) elif action == "package-check": self.check_packages(peer) elif action == "package-result": @@ -207,6 +229,7 @@ class PeerManagementView(OperatorAuthorization, FormView): peer.operator = self.request.user peer.enrolled_at = timezone.now() peer.revoked_at = None + peer.account_inventory_allowed = False peer.checked_at = None peer.save() except IntegrityError: diff --git a/src/coulobre/hosting/peering.py b/src/coulobre/hosting/peering.py index 5b63416..49908f9 100644 --- a/src/coulobre/hosting/peering.py +++ b/src/coulobre/hosting/peering.py @@ -2,6 +2,7 @@ import hashlib import json import secrets from datetime import timedelta +from http.client import HTTPException from importlib.metadata import version from pathlib import Path from urllib.error import HTTPError, URLError @@ -38,6 +39,7 @@ MAX_PEERS = 16 TIMEOUT = 4 MAX_PACKET = 4096 MAX_REPLY = 16384 +MAX_INVENTORY_REPLY = 49152 MAX_AGE = 30 CLOCK_SKEW = 10 GRANT_AGE = timedelta(minutes=5) @@ -157,20 +159,23 @@ def peer_call(peer, action, actor="", value=""): headers={"Content-Type": "application/json"}, ) opener = build_opener(NoRedirect(), ProxyHandler({})) + max_reply = ( + MAX_INVENTORY_REPLY if action == "account-inventory" else MAX_REPLY + ) try: with opener.open(request, timeout=TIMEOUT) as response: - raw = response.read(MAX_REPLY + 1) + raw = response.read(max_reply + 1) except HTTPError as error: if error.code == 403: raise PeerAccessError("The peer denied this request.") from None raise PeerAccessError( "The peer could not complete this request." ) from None - except (URLError, OSError): + except (URLError, OSError, HTTPException): raise PeerAccessError( "The peer did not respond over verified HTTPS." ) from None - if len(raw) > MAX_REPLY: + if len(raw) > max_reply: raise PeerAccessError("The peer returned an oversized reply.") reply, signature = read_message(raw) verify(peer.public_key, reply, signature) @@ -205,7 +210,8 @@ def authorize_message(message, signature): or not isinstance(message["actor"], str) or len(message["actor"]) > 150 or not isinstance(message["value"], str) - or len(message["value"]) > 128 + or len(message["value"]) + > (600 if message["action"] == "account-inventory" else 128) ): raise PeerAccessError("The peer request is invalid or expired.") parse_reference(message["request"]) diff --git a/src/coulobre/hosting/static/hosting/panel.css b/src/coulobre/hosting/static/hosting/panel.css index 7335d36..41c6062 100644 --- a/src/coulobre/hosting/static/hosting/panel.css +++ b/src/coulobre/hosting/static/hosting/panel.css @@ -1400,3 +1400,13 @@ dd { .workspace-list li + li { margin-top: 0.4rem; } + +.hosting-node-full { + display: none; + overflow-wrap: anywhere; +} + +.hosting-node:hover .hosting-node-full, +.hosting-node:focus .hosting-node-full { + display: block; +} diff --git a/src/coulobre/hosting/templates/hosting/account_list.html b/src/coulobre/hosting/templates/hosting/account_list.html index 9c3dc85..32cf2ed 100644 --- a/src/coulobre/hosting/templates/hosting/account_list.html +++ b/src/coulobre/hosting/templates/hosting/account_list.html @@ -13,6 +13,7 @@ {% endif %} {% endblock %} +{% block page_tabs %}{% include "hosting/hosting_account_tabs.html" %}{% endblock %} {% block page_context %}