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 %}
{% endif %} + {% if local_hosting_node %}{% include "hosting/hosting_node.html" with node=local_hosting_node only %}{% endif %} {% include "hosting/account_status.html" %} {% if is_operator and perms.hosting.view_customer %}{{ account.customer|default_if_none:"No customer linked" }}{% endif %} {% if is_tenant or perms.hosting.view_hostingplan %} diff --git a/src/coulobre/hosting/templates/hosting/cluster_account_list.html b/src/coulobre/hosting/templates/hosting/cluster_account_list.html new file mode 100644 index 0000000..12d1d94 --- /dev/null +++ b/src/coulobre/hosting/templates/hosting/cluster_account_list.html @@ -0,0 +1,65 @@ +{% extends "hosting/workspace_page.html" %} +{% block title %}Hosting accounts · Coulobre Panel{% endblock %} +{% block page_title %}Hosting accounts{% endblock %} +{% block page_metadata %} +

Find accounts across enrolled panels. Open an account on the panel that hosts it.

+{% endblock %} +{% block page_actions %} + Add account on this node +{% endblock %} +{% block page_tabs %}{% include "hosting/hosting_account_tabs.html" %}{% endblock %} +{% block page_context %} +
+ + + + + + + {% if search or selected_node %}Clear{% endif %} + +
+{% endblock %} +{% block page_content %} + {% if unavailable_nodes %} +

Results may be incomplete. Could not read the hosting inventory on {% for node in unavailable_nodes %}{{ node.label }}{% if not forloop.last %}, {% endif %}{% endfor %}. Check that the peer is reachable and allows inventory sharing.

+ {% endif %} +
+
+ + + {% for page in pages %} + {% if not page.unavailable %} + + {% for account in page.accounts %} + + + + + + {% empty %} + + + + {% endfor %} + {% if page.more and not selected_node %} + + {% endif %} + + {% endif %} + {% endfor %} +
AccountHosting nodeStatus
{{ account.name }}{% include "hosting/hosting_node.html" with node=page.node only %}{% include "hosting/account_status.html" %}
No matching accounts on {{ page.node.label }}{% if previous_offset is not None %} on this page{% endif %}.
View all results on {{ page.node.label }}
+
+ {% if previous_offset is not None or next_offset is not None %} + + {% endif %} +
+{% endblock %} diff --git a/src/coulobre/hosting/templates/hosting/hosting_account_tabs.html b/src/coulobre/hosting/templates/hosting/hosting_account_tabs.html new file mode 100644 index 0000000..190b90e --- /dev/null +++ b/src/coulobre/hosting/templates/hosting/hosting_account_tabs.html @@ -0,0 +1,6 @@ +{% if cluster_nodes %} + +{% endif %} diff --git a/src/coulobre/hosting/templates/hosting/hosting_node.html b/src/coulobre/hosting/templates/hosting/hosting_node.html new file mode 100644 index 0000000..7621d92 --- /dev/null +++ b/src/coulobre/hosting/templates/hosting/hosting_node.html @@ -0,0 +1,5 @@ +{% if node.label == node.authority %} + {{ node.label }} +{% else %} + {{ node.label }} +{% endif %} diff --git a/src/coulobre/hosting/templates/hosting/panel_peers.html b/src/coulobre/hosting/templates/hosting/panel_peers.html index ff231f8..07c1be3 100644 --- a/src/coulobre/hosting/templates/hosting/panel_peers.html +++ b/src/coulobre/hosting/templates/hosting/panel_peers.html @@ -45,6 +45,17 @@ {% if request.user.pk == peer.operator_id %} +
Hosting inventory sharing · {% if peer.account_inventory_allowed %}On{% else %}Off{% endif %} +
+ {% csrf_token %} +

Allow the mapped operator on this peer to list this panel's account names, domains and status.

+ {% if peer.account_inventory_allowed %} + + {% else %} + + {% endif %} +
+
{% if peer.status.can_check_packages %}
Check peer packages
diff --git a/src/coulobre/hosting/test_cluster_accounts.py b/src/coulobre/hosting/test_cluster_accounts.py new file mode 100644 index 0000000..9f0d655 --- /dev/null +++ b/src/coulobre/hosting/test_cluster_accounts.py @@ -0,0 +1,166 @@ +from unittest.mock import patch + +from django.contrib.auth import get_user_model +from django.test import TestCase, override_settings +from django.urls import reverse +from django.utils import timezone +from django_otp import DEVICE_ID_SESSION_KEY +from django_otp.plugins.otp_totp.models import TOTPDevice + +from .cluster_accounts import PAGE_SIZE +from .models import HostingAccount, PanelPeer +from .peering import PeerAccessError + + +@override_settings(PASSWORD_RESET_ORIGIN="https://web1.a.cluster.example") +class ClusterAccountTests(TestCase): + @classmethod + def setUpTestData(cls): + cls.operator = get_user_model().objects.create_superuser("mapped") + cls.device = TOTPDevice.objects.create(user=cls.operator, name="test") + cls.local = HostingAccount.objects.create( + name="Local hosting", primary_domain="local.example.test" + ) + cls.peer = PanelPeer.objects.create( + origin="https://web2.cluster.example", + public_key="ab" * 32, + remote_username="remote-operator", + operator=cls.operator, + ) + cls.customer = get_user_model().objects.create_user("customer") + cls.cluster = reverse("panel:cluster_accounts") + cls.local_list = reverse("panel:accounts") + + def sign_in(self): + self.client.force_login(self.operator) + session = self.client.session + session[DEVICE_ID_SESSION_KEY] = self.device.persistent_id + session.save() + + def remote_result(self, *, count=1, more=False): + return { + "accounts": [ + { + "id": number, + "name": f"Remote site {number}", + "primary_domain": f"remote{number}.example.test", + "services_suspended": True, + } + for number in range(1, count + 1) + ], + "more": more, + } + + def test_short_name_and_links_point_to_owner(self): + self.sign_in() + local = self.client.get(self.local_list) + self.assertContains(local, "This node") + self.assertContains(local, "All nodes") + self.assertContains(local, 'aria-label="web1.a.cluster.example"') + self.assertContains(local, ">web1<") + with patch( + "coulobre.hosting.cluster_accounts.peer_call", + return_value=self.remote_result(), + ) as exchange: + response = self.client.get(self.cluster) + self.assertContains(response, self.local.get_absolute_url()) + self.assertContains(response, "Remote site 1") + self.assertContains( + response, + self.peer.origin + reverse("panel:account", kwargs={"pk": 1}), + ) + self.assertContains(response, ">web2<") + self.assertContains(response, 'aria-label="web2.cluster.example"') + self.assertIn("no-store", response.headers["Cache-Control"]) + exchange.assert_called_once_with( + self.peer, "account-inventory", "mapped", '{"q": "", "offset": 0}' + ) + + def test_hostname_collision_only_expands_colliding_labels(self): + PanelPeer.objects.create( + origin="https://web1.b.cluster.example", + public_key="cd" * 32, + remote_username="collision", + operator=self.operator, + ) + self.sign_in() + response = self.client.get(self.cluster, {"node": "local"}) + self.assertContains(response, ">web1.a<") + labels = [node.label for node in response.context["cluster_nodes"]] + self.assertEqual(labels, ["web1.a", "web1.b", "web2"]) + + def test_filter_and_search_visit_only_selected_node_and_can_page(self): + self.sign_in() + with patch( + "coulobre.hosting.cluster_accounts.peer_call", + return_value=self.remote_result(count=PAGE_SIZE, more=True), + ) as exchange: + response = self.client.get( + self.cluster, + {"node": self.peer.pk, "q": "remote", "offset": 20}, + ) + self.assertNotContains(response, self.local.name) + self.assertContains(response, "Previous") + self.assertContains(response, "Next") + self.assertContains(response, "offset=40") + exchange.assert_called_once_with( + self.peer, + "account-inventory", + "mapped", + '{"q": "remote", "offset": 20}', + ) + + def test_unavailable_or_invalid_peer_results_do_not_hide_local_accounts( + self, + ): + self.sign_in() + for result in ( + PeerAccessError("Peer unavailable"), + self.remote_result() | {"unexpected": True}, + ): + with ( + self.subTest(result=result), + patch( + "coulobre.hosting.cluster_accounts.peer_call", + **( + {"side_effect": result} + if isinstance(result, Exception) + else {"return_value": result} + ), + ), + ): + response = self.client.get(self.cluster) + self.assertContains(response, "Results may be incomplete") + self.assertContains(response, self.local.name) + self.assertNotContains(response, "Remote site") + + def test_only_mapped_verified_operators_can_use_inventory(self): + self.client.force_login(self.operator) + self.assertEqual(self.client.get(self.cluster).status_code, 403) + self.client.force_login(self.customer) + self.assertEqual(self.client.get(self.cluster).status_code, 403) + self.sign_in() + other = get_user_model().objects.create_superuser("unmapped") + PanelPeer.objects.filter(pk=self.peer.pk).update(operator=other) + with patch("coulobre.hosting.cluster_accounts.peer_call") as exchange: + self.assertEqual(self.client.get(self.cluster).status_code, 404) + self.assertNotContains( + self.client.get(self.local_list), "All nodes" + ) + exchange.assert_not_called() + + def test_revoked_peer_and_unknown_filters_are_not_available(self): + self.sign_in() + self.assertEqual( + self.client.get(self.cluster, {"node": "999"}).status_code, 404 + ) + self.assertEqual( + self.client.get(self.cluster, {"offset": "20"}).status_code, 404 + ) + PanelPeer.objects.filter(pk=self.peer.pk).update( + revoked_at=timezone.now() + ) + self.assertEqual(self.client.get(self.cluster).status_code, 404) + self.assertNotContains( + self.client.get(self.local_list), "Hosting node" + ) 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( diff --git a/src/coulobre/hosting/urls.py b/src/coulobre/hosting/urls.py index 6ca84b3..25f7526 100644 --- a/src/coulobre/hosting/urls.py +++ b/src/coulobre/hosting/urls.py @@ -22,6 +22,7 @@ from .account_security import ( ) from .backup_restores import RestoreKind from .certificate_views import customer_certificates, operator_certificates +from .cluster_account_views import ClusterAccountList from .credential_views import DatabaseCredentialView, MailboxCredentialView from .customer_backup_views import CustomerBackupView, CustomerRestoreView from .database_login_views import ( @@ -328,6 +329,11 @@ urlpatterns = [ name="smtp_applications", ), path("", views.AccountList.as_view(), name="accounts"), + path( + "accounts/cluster/", + ClusterAccountList.as_view(), + name="cluster_accounts", + ), path( "service-health/", ServiceHealthView.as_view(), name="service_health" ), diff --git a/src/coulobre/hosting/views.py b/src/coulobre/hosting/views.py index f9a75b4..0494e51 100644 --- a/src/coulobre/hosting/views.py +++ b/src/coulobre/hosting/views.py @@ -74,6 +74,7 @@ from .backup_restores import ( retry_remote_mail_restore, ) from .backup_retention import change_backup_retention, protect_backup +from .cluster_accounts import inventory_nodes from .dns_defaults import hosting_address_choices, zone_defaults from .dns_forms import ( DnsZoneEditForm, @@ -400,6 +401,9 @@ class AccountList(TenantScopeMixin, PermissionRequiredMixin, ListView): def get_context_data(self, **kwargs): context = super().get_context_data(search=self.search, **kwargs) + if nodes := inventory_nodes(self.request): + context["cluster_nodes"] = nodes + context["local_hosting_node"] = nodes[0] if not self.search and not self.request.GET.get("customer"): context["onboarding"] = onboarding_context(self.request) context["show_customer_website_link"] = settings.WEBSITE_USAGE diff --git a/src/coulobre/hosting/workspaces.py b/src/coulobre/hosting/workspaces.py index 4c3b3cd..e09e156 100644 --- a/src/coulobre/hosting/workspaces.py +++ b/src/coulobre/hosting/workspaces.py @@ -75,6 +75,7 @@ CUSTOMER_NAV_ROUTES = { } WORKSPACE_PARENT_ROUTES = { + "cluster_accounts": ("accounts", ()), "user_delete": ("all_users", ()), "remote_deploy": ("connected_nodes", ()), "dns_topology": ("dns_defaults", ()),