From 2719fe2dce9d2dc415b271ee297b40eb5edeeab3 Mon Sep 17 00:00:00 2001 From: Peter van Arkel Date: Thu, 3 Dec 2026 11:59:28 +0100 Subject: [PATCH] Share scoped hosting account summaries with enrolled panels --- src/coulobre/hosting/cluster_accounts.py | 225 ++++++++++++++++++ .../0091_panel_peer_account_inventory.py | 17 ++ src/coulobre/hosting/models.py | 1 + src/coulobre/hosting/peer_views.py | 25 +- src/coulobre/hosting/peering.py | 14 +- src/coulobre/hosting/test_peering.py | 87 ++++++- 6 files changed, 363 insertions(+), 6 deletions(-) create mode 100644 src/coulobre/hosting/cluster_accounts.py create mode 100644 src/coulobre/hosting/migrations/0091_panel_peer_account_inventory.py 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/test_peering.py b/src/coulobre/hosting/test_peering.py index d972ea8..8eeebf8 100644 --- a/src/coulobre/hosting/test_peering.py +++ b/src/coulobre/hosting/test_peering.py @@ -9,7 +9,12 @@ from django.utils import timezone from django_otp import DEVICE_ID_SESSION_KEY from django_otp.plugins.otp_totp.models import TOTPDevice -from .models import OperatorOperation, PanelPeer, PeerActionGrant +from .models import ( + HostingAccount, + OperatorOperation, + PanelPeer, + PeerActionGrant, +) from .peering import ( PROTOCOL, PeerAccessError, @@ -83,6 +88,86 @@ class PanelPeerTests(TestCase): self.call_target(self.source_message("status")).status_code, 403 ) + def test_account_inventory_requires_explicit_directional_sharing(self): + matching = HostingAccount.objects.create( + name="Matching site", primary_domain="match.example.test" + ) + HostingAccount.objects.create( + name="Excluded", primary_domain="excluded.example.test" + ) + HostingAccount.objects.create( + name="Matching retired", + primary_domain="retired.example.test", + retired_at=timezone.now(), + ) + value = json.dumps({"q": "match", "offset": 0}) + + def signed_query(username="source", query=value): + return self.call_target( + self.source_message("account-inventory", username, query) + ) + + self.assertEqual(signed_query().status_code, 403) + self.client.force_login(self.operator) + session = self.client.session + session[DEVICE_ID_SESSION_KEY] = self.device.persistent_id + session.save() + page = reverse("panel:panel_peers") + self.assertEqual( + self.client.post( + page, {"peer": self.peer.pk, "action": "allow-inventory"} + ).status_code, + 302, + ) + self.assertEqual(signed_query(username="other").status_code, 403) + result = signed_query().json() + verify(panel_public_key(), result["message"], result["signature"]) + self.assertEqual( + result["message"]["result"], + { + "accounts": [ + { + "id": matching.pk, + "name": matching.name, + "primary_domain": matching.primary_domain, + "services_suspended": False, + } + ], + "more": False, + }, + ) + for offset in (-1, True, 1_000_001): + self.assertEqual( + signed_query( + query=json.dumps({"q": "", "offset": offset}) + ).status_code, + 403, + ) + self.assertEqual( + self.client.post( + page, {"peer": self.peer.pk, "action": "deny-inventory"} + ).status_code, + 302, + ) + self.assertEqual(signed_query().status_code, 403) + + def test_unmapped_operator_cannot_enable_inventory_for_peer(self): + other = get_user_model().objects.create_superuser("unmapped") + device = TOTPDevice.objects.create(user=other, name="test") + self.client.force_login(other) + session = self.client.session + session[DEVICE_ID_SESSION_KEY] = device.persistent_id + session.save() + self.assertEqual( + self.client.post( + reverse("panel:panel_peers"), + {"peer": self.peer.pk, "action": "allow-inventory"}, + ).status_code, + 403, + ) + self.peer.refresh_from_db() + self.assertFalse(self.peer.account_inventory_allowed) + def test_package_check_enforces_operator_mapping_and_reuses_grant(self): grant = issue_grant(self.peer, self.operator) with patch(