Files
paskia/paskia/util/hostutil.py
T
LeoVasanko f2e6f5784e Rename realms to domains; object-keyed origins/related config format
Finish the realm→domain terminology removal across source, tests, e2e
and docs. The stored config drops all lists: Config.domains is keyed by
rp-id, DomainConfig.origins/related are objects keyed by host (https://
omitted), values True or OriginEntry(auth_host=True). The default/primary
domain concept is gone; ordering is display-time. Tests and e2e updated
to the new API shapes (not run). Database re-migrated from the legacy
backup into the new format.
2026-09-07 02:05:12 +00:00

110 lines
3.6 KiB
Python

"""Utilities for host/origin normalization and validation."""
import re
from urllib.parse import urlparse, urlsplit
_RP_ID_RE = re.compile(
r"^[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(\.[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$"
)
def validate_rp_id(rp_id: str) -> None:
"""Validate that rp_id is a valid domain name (or localhost)."""
if not rp_id:
raise ValueError("rp_id cannot be empty")
if rp_id == "localhost":
return
if not _RP_ID_RE.match(rp_id):
raise ValueError(f"rp_id '{rp_id}' is not a valid domain name")
def is_wildcard_pattern(value: str) -> bool:
"""Check whether an origins entry is a wildcard pattern like '*.example.com'."""
return value.startswith("*.")
def normalize_origin(origin: str) -> str:
"""Normalize an origin URL by adding https:// if no scheme is present, removing trailing slashes.
Wildcard patterns ('*.example.com') pass through unchanged — they are
allow-list entries, not concrete origins.
"""
if is_wildcard_pattern(origin):
return origin.rstrip("/.")
if "://" not in origin:
return f"https://{origin}"
return origin.rstrip("/")
def origin_hostname(origin: str) -> str | None:
"""Extract the lowercase hostname from an origin URL, if well-formed.
For wildcard patterns the base domain is returned.
"""
if is_wildcard_pattern(origin):
return origin[2:].rstrip(".").lower() or None
return urlparse(origin).hostname
def is_subdomain(sub: str, domain: str) -> bool:
"""Check if sub is a subdomain of domain (or equal)."""
sub_parts = sub.lower().split(".")
domain_parts = domain.lower().split(".")
if len(sub_parts) < len(domain_parts):
return False
return sub_parts[-len(domain_parts) :] == domain_parts
def validate_auth_host(auth_host: str, rp_id: str) -> None:
"""Validate that auth_host is a subdomain of rp_id.
Raises ValueError on invalid auth_host.
"""
parsed = urlparse(auth_host if "://" in auth_host else f"//{auth_host}")
host = parsed.hostname or parsed.path
if not host:
raise ValueError(f"Invalid auth-host: '{auth_host}'")
if not is_subdomain(host, rp_id):
raise ValueError(
f"auth-host '{auth_host}' is not a subdomain of rp-id '{rp_id}'"
)
def auth_host_netloc(auth_host: str) -> str | None:
"""Return the host[:port] part of a configured auth host URL."""
parsed = urlparse(auth_host if "://" in auth_host else f"//{auth_host}")
return parsed.netloc or parsed.path or None
def normalize_host(raw_host: str | None) -> str | None:
"""Normalize a Host header, stripping port numbers and trailing dots."""
if not raw_host:
return None
candidate = raw_host.strip()
if not candidate:
return None
# urlsplit to parse (add // for scheme-less); prefer netloc to retain port.
parsed = urlsplit(candidate if "//" in candidate else f"//{candidate}")
netloc = parsed.netloc or parsed.path or ""
# Handle IPv6 addresses: [ipv6]:port or [ipv6]
if netloc.startswith("["):
if "]" in netloc:
host_part, _, _ = netloc.partition("]")
netloc = host_part.strip("[]")
else:
# Strip port from host:port
netloc = netloc.rsplit(":", 1)[0]
return netloc.lower().rstrip(".") or None
def format_endpoint(ep: dict) -> str:
"""Format an endpoint dict to a listen string (e.g. 'unix:/path' or 'host:port')."""
if uds := ep.get("uds"):
return f"unix:{uds}"
host = ep["host"]
port = ep["port"]
# Bracket IPv6 addresses
if ":" in host:
host = f"[{host}]"
return f"{host}:{port}"