226 lines
6.6 KiB
Python
226 lines
6.6 KiB
Python
"""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
|