From 8c2809a879eb752932ca477bbe625060ae63e490 Mon Sep 17 00:00:00 2001 From: Leo Vasanko Date: Sat, 5 Sep 2026 14:35:49 +0000 Subject: [PATCH 01/48] Update fastapi-vue-setup, make use of its access logging facility. --- frontend/vite-plugin-fastapi.js | 2 + paskia/__main__.py | 9 +- paskia/fastapi/logging.py | 249 +----------------- paskia/fastapi/mainapp.py | 13 +- paskia/fastapi/wsutil.py | 12 +- pyproject.toml | 2 +- scripts/devserver.py | 3 + .../{build-frontend.py => buildhook.py} | 10 +- scripts/fastapi-vue/buildutil.py | 156 +++++++---- scripts/fastapi-vue/devutil.py | 114 +++++--- 10 files changed, 204 insertions(+), 366 deletions(-) rename scripts/fastapi-vue/{build-frontend.py => buildhook.py} (50%) diff --git a/frontend/vite-plugin-fastapi.js b/frontend/vite-plugin-fastapi.js index ffef157..e7e5945 100644 --- a/frontend/vite-plugin-fastapi.js +++ b/frontend/vite-plugin-fastapi.js @@ -5,6 +5,7 @@ * Configures Vite for FastAPI backend integration: * - Proxies /api/* requests to the FastAPI backend * - Builds to the Python module's frontend-build directory + * - Disables Vite's screen clearing on startup * * Options: * paths - Array of paths to proxy (default: ["/api"]) @@ -26,6 +27,7 @@ export default function fastapiVue({ paths = ["/api"] } = {}) { return { name: "vite-plugin-fastapi-paskia", config: () => ({ + clearScreen: false, server: { proxy }, build: { outDir: "../paskia/frontend-build", diff --git a/paskia/__main__.py b/paskia/__main__.py index a66b1b0..4c4a15f 100644 --- a/paskia/__main__.py +++ b/paskia/__main__.py @@ -166,14 +166,15 @@ def main(): os.environ["PASKIA_CONFIG"] = msgspec.json.encode(runtime).decode() # Run the server (spawns processes in dev mode) - dev = {"reload": True, "reload_dirs": ["paskia"]} if DEVMODE else {} + # tracerite, access logging and log config are handled by fastapi_vue.server; + # we print our own startup config box, so disable the built-in one. server.run( "paskia.fastapi.mainapp:app", listen=config.listen, default_port=DEFAULT_PORT, - log_level="warning", - access_log=False, - **dev, + server_header=False, + startup_box=None, + reload=Path(__file__).parent if DEVMODE else False, ) diff --git a/paskia/fastapi/logging.py b/paskia/fastapi/logging.py index 60a19db..6b74657 100644 --- a/paskia/fastapi/logging.py +++ b/paskia/fastapi/logging.py @@ -1,34 +1,19 @@ -"""Custom access logging middleware for FastAPI/Uvicorn.""" +"""Authorization-related logging. + +HTTP/WebSocket access logging is handled by fastapi_vue's ASGI middleware +(installed via fastapi_vue.server.run); request handlers can pass extra +details to the access log line via request.state.log_extra. +""" import logging -import sys -import time -from ipaddress import IPv6Address from typing import TYPE_CHECKING -from starlette.middleware.base import BaseHTTPMiddleware - if TYPE_CHECKING: from paskia.db.structs import SessionContext -from starlette.requests import Request -from starlette.responses import Response logger = logging.getLogger("paskia.access") _RESET = "\033[0m" -_STATUS_INFO = "\033[32m" # 1xx (green) -_STATUS_OK = "\033[1;92m" # 2xx (bright green) -_STATUS_REDIRECT = "\033[32m" # 3xx (green) -_STATUS_CLIENT_ERR = "\033[0;31m" # 4xx (red) -_STATUS_SERVER_ERR = "\033[1;91m" # 5xx (bold bright red) -_METHOD_READ = "\033[0;34m" # GET, HEAD, OPTIONS (blue) -_METHOD_WRITE = "\033[1;94m" # POST, PUT, DELETE, PATCH (bold bright blue) -_HOST = "\033[38;5;242m" # hostname (dark grey) -_PATH = "\033[38;5;250m" # path (white) -_TIMING = "\033[38;5;242m" # timing/devmode (dark grey) -_WS_OPEN = "\033[38;5;226m" # WebSocket connect (brightest yellow from 6x6x6 cube) -_WS_CLOSE = "\033[38;5;142m" # WebSocket disconnect (significantly dimmer yellow) -_WS_STATUS = "\033[38;5;242m" # WebSocket close status (dark grey) _AUTHZ_DENIED = "\033[0;31m" # Permission denied (red) _AUTHZ_USER = "\033[1;34m" # User info (light blue) _AUTHZ_ORG = "\033[34m" # User info (blue) @@ -37,191 +22,6 @@ _AUTHZ_MISSING = "\033[1;31m" # Missing scope (bold red) _AUTHZ_GRANTED = "\033[0;32m" # Granted scope (green) -def format_ipv6_network(ip: str) -> str: - """Format IPv6 address to show only network part (first 64 bits). - - Special addresses are returned as-is for clarity: - - ::1 (loopback) - - :: (unspecified) - - ::ffff:x.x.x.x (IPv4-mapped, returns just the IPv4 part) - - fe80:: (link-local, returned as-is since interface-specific) - """ - try: - # Strip brackets that some proxies add around IPv6 - ip = ip.strip("[]") - # Strip zone ID (e.g., fe80::1%eth0) - if "%" in ip: - ip = ip.split("%")[0] - addr = IPv6Address(ip) - - # Special cases - return as-is or with minimal processing - if addr.is_loopback: # ::1 - return "::1" - if addr.is_unspecified: # :: - return "::" - if addr.ipv4_mapped: # ::ffff:x.x.x.x - return str(addr.ipv4_mapped) - if addr.is_link_local: # fe80::/10 - interface-specific, keep full - return str(addr) - - # Regular addresses: truncate to /64 network prefix - network_int = int(addr) >> 64 - # Format as IPv6 with trailing :: - # Split into 4 groups of 16 bits - groups = [] - for _ in range(4): - groups.insert(0, format(network_int & 0xFFFF, "x")) - network_int >>= 16 - # Compress consecutive zero groups - result = ":".join(groups) + "::" - # Simplify leading zeros in groups and compress, then strip trailing :: - return str(IPv6Address(result + "0")).removesuffix("::") - except Exception: - return ip - - -def format_client_ip(ip: str) -> str: - """Format client IP, compressing IPv6 to network part only.""" - if not ip or ip == "-": - return "-" - # Strip brackets for detection (some proxies add them) - stripped = ip.strip("[]") - if ":" in stripped: - return format_ipv6_network(ip) - return ip - - -def status_color(status: int) -> str: - """Return color code based on HTTP status.""" - if status < 200: - return _STATUS_INFO - if status < 300: - return _STATUS_OK - if status < 400: - return _STATUS_REDIRECT - if status < 500: - return _STATUS_CLIENT_ERR - return _STATUS_SERVER_ERR - - -def method_color(method: str) -> str: - """Return color code based on HTTP method.""" - if method in ("GET", "HEAD", "OPTIONS"): - return _METHOD_READ - return _METHOD_WRITE - - -def format_access_log( - client: str, - status: int, - method: str, - host: str, - path: str, - duration_ms: float, - extra: str = "", -) -> str: - """Format access log line with colors and aligned fields.""" - # Format components with fixed widths for alignment - ip = format_client_ip(client).ljust(19) # IPv6 network max 19 chars - timing = f"{duration_ms:.0f}ms" - method_padded = method.ljust(7) # Longest method is OPTIONS (7) - - status_str = f"{status_color(status)}{status}{_RESET}" - timing_str = f"{_TIMING}{timing}{_RESET}" - method_str = f"{method_color(method)}{method_padded}{_RESET}" - host_str = f"{_HOST}{host}{_RESET}" - path_str = f"{_PATH}{path}{_RESET}" - - # Format: "IP STATUS METHOD host path [extra] TIMING" - extra_str = f" {_TIMING}{extra}{_RESET}" if extra else "" - return ( - f"{ip} {status_str} {method_str} {host_str}{path_str}{extra_str} {timing_str}" - ) - - -# WebSocket connection counter (mod 100) -_ws_counter = 0 - - -def _next_ws_id() -> int: - """Get next WebSocket connection ID (0-99).""" - global _ws_counter - ws_id = _ws_counter - _ws_counter = (_ws_counter + 1) % 100 - return ws_id - - -def log_ws_open(ws) -> int: - """Log WebSocket connection open. Returns connection ID for use in close.""" - ws_id = _next_ws_id() - - client = ws.client.host if ws.client else "-" - host = ws.headers.get("host", "-") - path = ws.url.path - origin = ws.headers.get("origin") - - ip = format_client_ip(client).ljust(19) - # ID right-aligned like status codes (3 chars), emoji formatted like method - id_str = f"{_WS_OPEN}{str(ws_id).rjust(3)}{_RESET}" - # Emoji (2 display width) + 6 spaces = 8 display chars, but within color for alignment - emoji_str = f"{_METHOD_READ}๐Ÿ”Œ {_RESET}" - - # Determine if origin should be shown (omit when same as host) - # Origin header includes scheme (e.g., "https://example.com"), compare host part - origin_host = origin.split("://", 1)[-1] if origin else None - show_origin = origin_host and origin_host != host - - host_str = f"{_HOST}{host}{_RESET}" - path_str = f"{_PATH}{path}{_RESET}" - origin_str = f" {_RESET}from {_HOST}{origin_host}{_RESET}" if show_origin else "" - - logger.info(f"{ip} {id_str} {emoji_str}{host_str}{path_str}{origin_str}") - return ws_id - - -# WebSocket close codes to human-readable status -WS_CLOSE_CODES = { - 1000: "ok", - 1001: "going away", - 1002: "protocol error", - 1003: "unsupported", - 1005: "no status", - 1006: "abnormal", - 1007: "invalid data", - 1008: "policy violation", - 1009: "too large", - 1010: "extension required", - 1011: "server error", - 1012: "restarting", - 1013: "try again", - 1014: "bad gateway", - 1015: "tls error", -} - - -def log_ws_close(ws_id: int, close_code: int | None, duration: float) -> None: - """Log WebSocket connection close with duration and status.""" - # ID right-aligned like status codes (3 chars), "closed" formatted like method - id_str = f"{_WS_CLOSE}{str(ws_id).rjust(3)}{_RESET}" - # Pad within the dim color to keep full width in color (8 display chars) - closed_str = f"{_TIMING}closed {_RESET}" - timing = f"{duration * 1000:.0f}ms" - - # Convert close code to status text - if close_code is None: - code = "----" - status = "unknown" - else: - code = str(close_code) - status = WS_CLOSE_CODES.get(close_code, f"code {close_code}") - - # Status code and text in normal color, not dim - status_str = f"{code} {status}" - timing_str = f"{_TIMING}{timing}{_RESET}" - - logger.info(f"{' ' * 19} {id_str} {closed_str}{status_str} {timing_str}") - - def log_permission_denied( ctx: SessionContext, required: list[str], missing: list[str], *, require_all: bool ) -> None: @@ -240,40 +40,3 @@ def log_permission_denied( f"{_AUTHZ_ORG}({ctx.org.display_name} {ctx.role.display_name}){_RESET} " f"{_AUTHZ_NEEDS}needs{n}:{_RESET} {scopes}" ) - - -class AccessLogMiddleware(BaseHTTPMiddleware): - """Middleware that logs HTTP requests with custom format.""" - - async def dispatch(self, request: Request, call_next) -> Response: - start = time.perf_counter() - response = await call_next(request) - duration_ms = (time.perf_counter() - start) * 1000 - - client = request.client.host if request.client else "-" - host = request.headers.get("host", "-") - method = request.method - path = request.url.path - if request.url.query: - path = f"{path}?{request.url.query}" - status = response.status_code - - extra = getattr(request.state, "log_extra", "") - - line = format_access_log( - client, status, method, host, path, duration_ms, extra=extra - ) - logger.info(line) - - return response - - -def configure_access_logging(): - """Configure the access logger to output to stderr.""" - handler = logging.StreamHandler(sys.stderr) - handler.setFormatter(logging.Formatter("%(message)s")) - logger.addHandler(handler) - logger.setLevel(logging.INFO) - logger.propagate = False - # Suppress watchfiles "X changes detected" INFO messages (keep WARNING for reload notification) - logging.getLogger("watchfiles.main").setLevel(logging.WARNING) diff --git a/paskia/fastapi/mainapp.py b/paskia/fastapi/mainapp.py index d502c8f..55494c1 100644 --- a/paskia/fastapi/mainapp.py +++ b/paskia/fastapi/mainapp.py @@ -18,18 +18,14 @@ from paskia.fastapi.admin.adminapp import adminapp # Import frontend instance from paskia.fastapi.front import frontend -from paskia.fastapi.logging import AccessLogMiddleware, configure_access_logging from paskia.fastapi.session import AUTH_COOKIE from paskia.util import hostutil, passphrase, vitedev from paskia.util.constants import DEVMODE from paskia.util.runtime import RuntimeConfig # Configure custom logging -configure_access_logging() configure_kanta_logging() -_access_logger = logging.getLogger("paskia.access") - # Path to examples/index.html when running from source tree _EXAMPLES_DIR = Path(__file__).parent.parent.parent / "examples" @@ -61,11 +57,6 @@ async def lifespan(app: FastAPI): # pragma: no cover - startup path if runtime.save: db.update_config(runtime.config) - # Restore uvicorn info logging (suppressed during startup in dev mode) - # Keep uvicorn.error at WARNING to suppress WebSocket "connection open/closed" messages - if app.debug: - logging.getLogger("uvicorn").setLevel(logging.INFO) - logging.getLogger("uvicorn.error").setLevel(logging.WARNING) await frontend.load() await start_background() yield @@ -82,8 +73,8 @@ app = FastAPI( debug=DEVMODE, ) -# Custom access logging (uvicorn's access_log is disabled) -app.add_middleware(AccessLogMiddleware) +# WebSocket and HTTP access logging is handled by fastapi_vue's ASGI middleware; +# extra details are passed via request.state.log_extra (ASGI scope state). # Apply redirections to auth-host if configured (deny access to restricted endpoints, remove /auth/) app.middleware("http")(auth_host.redirect_middleware) diff --git a/paskia/fastapi/wsutil.py b/paskia/fastapi/wsutil.py index d2ebec4..d547915 100644 --- a/paskia/fastapi/wsutil.py +++ b/paskia/fastapi/wsutil.py @@ -3,7 +3,6 @@ Shared WebSocket utilities for FastAPI endpoints. """ import logging -import time from functools import wraps import base64url @@ -11,7 +10,6 @@ from fastapi import WebSocket, WebSocketDisconnect from webauthn.helpers.exceptions import InvalidAuthenticationResponse from paskia.fastapi import authz -from paskia.fastapi.logging import log_ws_close, log_ws_open from paskia.globals import passkey from paskia.util import pow @@ -21,15 +19,11 @@ def websocket_error_handler(func): @wraps(func) async def wrapper(ws: WebSocket, *args, **kwargs): - start = time.perf_counter() - ws_id = log_ws_open(ws) - close_code = None - try: await ws.accept() return await func(ws, *args, **kwargs) - except WebSocketDisconnect as e: - close_code = e.code + except WebSocketDisconnect: + pass except authz.AuthException as e: await ws.send_json( { @@ -42,8 +36,6 @@ def websocket_error_handler(func): except Exception: logging.exception("Internal Server Error") await ws.send_json({"status": 500, "detail": "Internal Server Error"}) - finally: - log_ws_close(ws_id, close_code, time.perf_counter() - start) return wrapper diff --git a/pyproject.toml b/pyproject.toml index 83a349a..395306b 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -21,7 +21,7 @@ dependencies = [ "pyjwt[crypto]>=2.11.0", "jsondiff>=2.2.1", "msgspec>=0.20.0", - "fastapi-vue>=1.1.0", + "fastapi-vue~=1.4.2", "ua-parser[regex]>=1.0.1", "kanta>=0.7.0", ] diff --git a/scripts/devserver.py b/scripts/devserver.py index ac5fda2..c30cf40 100755 --- a/scripts/devserver.py +++ b/scripts/devserver.py @@ -11,6 +11,8 @@ from contextlib import suppress from pathlib import Path from urllib.parse import urlparse +import tracerite + # Import utilities from scripts/fastapi-vue (not a package, so we adjust sys.path) sys.path.insert(0, str(Path(__file__).with_name("fastapi-vue"))) from devutil import ( # noqa: E402 @@ -193,6 +195,7 @@ async def run_devserver(args: argparse.Namespace, remaining: list[str]) -> None: def main(): + tracerite.load() parser = argparse.ArgumentParser(add_help=False) parser.add_argument( "-l", diff --git a/scripts/fastapi-vue/build-frontend.py b/scripts/fastapi-vue/buildhook.py similarity index 50% rename from scripts/fastapi-vue/build-frontend.py rename to scripts/fastapi-vue/buildhook.py index 152c48c..407e4bf 100644 --- a/scripts/fastapi-vue/build-frontend.py +++ b/scripts/fastapi-vue/buildhook.py @@ -1,15 +1,19 @@ +# ruff: noqa: INP001 """Hatch build hook for building Vue frontend during package build.""" import sys from pathlib import Path -from hatchling.builders.hooks.plugin.interface import BuildHookInterface # type: ignore +from hatchling.builders.hooks.plugin.interface import BuildHookInterface sys.path.insert(0, str(Path(__file__).parent)) from buildutil import build -class CustomBuildHook(BuildHookInterface): - def initialize(self, version, build_data): +class CustomBuildHook(BuildHookInterface): # type: ignore[misc] + """Hatch build hook that builds Vue frontend during package build.""" + + def initialize(self, version: str, build_data: dict) -> None: # type: ignore[override] + """Build frontend before package is built.""" super().initialize(version, build_data) build("frontend") diff --git a/scripts/fastapi-vue/buildutil.py b/scripts/fastapi-vue/buildutil.py index c2b641e..3150423 100644 --- a/scripts/fastapi-vue/buildutil.py +++ b/scripts/fastapi-vue/buildutil.py @@ -1,3 +1,4 @@ +# ruff: noqa: INP001 """Utilities used at build time and in devserver script. No dependencies.""" import logging @@ -7,6 +8,8 @@ import shutil import subprocess from pathlib import Path +MIN_NODE_VERSION = 20 + class _PrefixFormatter(logging.Formatter): """Formatter that adds prefix based on log level.""" @@ -30,82 +33,119 @@ def _check_node_version(node_path: str) -> None: Raises RuntimeError if version is too old or cannot be determined. """ try: - result = subprocess.run( - [node_path, "--version"], capture_output=True, text=True, check=True + result = subprocess.run( # noqa: S603 + [node_path, "--version"], + capture_output=True, + text=True, + check=True, ) version_str = result.stdout.strip() # Parse version like "v20.10.0" or "v18.17.1" match = re.match(r"v(\d+)", version_str) if match: major_version = int(match.group(1)) - if major_version >= 20: + if major_version >= MIN_NODE_VERSION: return - raise RuntimeError( - f"Node.js {version_str} found, but v20+ required (install with nvm)" - ) + msg = f"Node.js {version_str} found, but v{MIN_NODE_VERSION}+ required" + raise RuntimeError(msg) except subprocess.CalledProcessError, FileNotFoundError, ValueError: pass - raise RuntimeError("Could not determine Node.js version") + msg = "Could not determine Node.js version" + raise RuntimeError(msg) + + +def _validate_npm_runtime(tool: str) -> bool: + """Validate npm runtime by checking Node.js version. Returns True if valid.""" + node_path = shutil.which("node", path=str(Path(tool).parent)) + if node_path is None: + return False + try: + _check_node_version(node_path) + except RuntimeError: + return False + return True + + +def _find_runtime_from_env(options: list[str]) -> tuple[str, str] | None: + """Find runtime specified by JS_RUNTIME environment variable.""" + js_runtime_env = os.environ.get("JS_RUNTIME") + if not js_runtime_env: + return None + + js_runtime = js_runtime_env + js_path = Path(js_runtime) + runtime_name = js_path.name + + # Map node to npm + if runtime_name == "node": + runtime_name = "npm" + js_runtime = str(js_path.parent / "npm") if js_path.parent.name else "npm" + + for option in options: + if option != runtime_name and not runtime_name.startswith(option): + continue + + tool = shutil.which(js_runtime) + if tool is None: + msg = f"JS_RUNTIME={js_runtime_env}: {option} not found" + raise RuntimeError(msg) + + if option == "npm": + node_path = shutil.which("node", path=str(Path(tool).parent)) + if node_path is None: + msg = f"JS_RUNTIME={js_runtime_env}: node not found" + raise RuntimeError(msg) + _check_node_version(node_path) + + return tool, option + + msg = f"JS_RUNTIME={js_runtime_env} not recognized" + raise RuntimeError(msg) + + +def _auto_detect_runtime(options: list[str]) -> tuple[str, str]: + """Auto-detect JavaScript runtime from available options.""" + node_version_error: RuntimeError | None = None + + for option in options: + tool = shutil.which(option) + if not tool: + continue + + if option == "npm" and not _validate_npm_runtime(tool): + try: + node_path = shutil.which("node", path=str(Path(tool).parent)) + if node_path: + _check_node_version(node_path) + except RuntimeError as e: + node_version_error = e + continue + + return tool, option + + if node_version_error: + raise node_version_error + msg = "Node.js (v20+), Deno or Bun is required but none was found" + raise RuntimeError(msg) def find_js_runtime() -> tuple[str, str]: """Find a JavaScript runtime from JS_RUNTIME env or auto-detect. Returns (tool_path, tool_name) where tool_name is "deno", "npm", or "bun". - Raises JSRuntimeError if no suitable runtime is found. + Raises RuntimeError if no suitable runtime is found. """ options = ["npm", "deno", "bun"] - node_version_error: RuntimeError | None = None # Check for JS_RUNTIME environment variable - if js_runtime_env := os.environ.get("JS_RUNTIME"): - js_runtime = js_runtime_env - js_path = Path(js_runtime) - runtime_name = js_path.name - # Map node to npm - if runtime_name == "node": - runtime_name = "npm" - js_runtime = str(js_path.parent / "npm") if js_path.parent.name else "npm" - for option in options: - if option == runtime_name or runtime_name.startswith(option): - tool = shutil.which(js_runtime) - if tool is None: - raise RuntimeError( - f"JS_RUNTIME={js_runtime_env}: {option} not found" - ) - # Check Node.js version if using npm - if option == "npm": - node_path = shutil.which("node", path=str(Path(tool).parent)) - if node_path is None: - raise RuntimeError( - f"JS_RUNTIME={js_runtime_env}: node not found" - ) - _check_node_version(node_path) # Raises on failure - return tool, option - raise RuntimeError(f"JS_RUNTIME={js_runtime_env} not recognized") + if result := _find_runtime_from_env(options): + return result # Auto-detect - for option in options: - if tool := shutil.which(option): - # Check Node.js version if using npm - if option == "npm": - node_path = shutil.which("node", path=str(Path(tool).parent)) - if node_path is None: - continue - try: - _check_node_version(node_path) - except RuntimeError as e: - node_version_error = e - continue # Try next runtime - return tool, option - - # No runtime found - provide helpful error - if node_version_error: - raise node_version_error - raise RuntimeError("Node.js (v20+), Deno or Bun is required but none was found") + return _auto_detect_runtime(options) -def find_build_tool(): +def find_build_tool() -> tuple[list[str], list[str]]: """Find JavaScript runtime and construct install/build commands. Returns (install_cmd, build_cmd) tuples of command lists. @@ -143,7 +183,7 @@ def find_dev_tool() -> list[str]: if name == "bun": logger.warning( - "Bun has a bug in WS proxying (https://github.com/oven-sh/bun/issues/9882). Consider using npm instead." + "Bun has a WS proxy bug (github.com/oven-sh/bun/issues/9882). Consider npm.", ) return [tool, *dev_args[name]] @@ -176,16 +216,16 @@ def build(folder: str = "frontend") -> None: install_cmd, build_cmd = find_build_tool() except RuntimeError as e: logger.warning(e) - raise SystemExit(1) + raise SystemExit(1) from None - def run(cmd): + def run(cmd: list[str]) -> None: display_cmd = [Path(cmd[0]).stem, *cmd[1:]] logger.info("### %s", " ".join(display_cmd)) - subprocess.run(cmd, check=True, cwd=folder) + subprocess.run(cmd, check=True, cwd=folder) # noqa: S603 try: run(install_cmd) logger.info("") run(build_cmd) except subprocess.CalledProcessError: - raise SystemExit(1) + raise SystemExit(1) from None diff --git a/scripts/fastapi-vue/devutil.py b/scripts/fastapi-vue/devutil.py index bb8e0de..72b34b6 100644 --- a/scripts/fastapi-vue/devutil.py +++ b/scripts/fastapi-vue/devutil.py @@ -1,27 +1,33 @@ +# ruff: noqa: INP001 """Utilities meant for devserver script, used only in source repository with dev deps.""" import asyncio import subprocess import sys -from collections.abc import Coroutine from contextlib import suppress from pathlib import Path -from typing import Any +from typing import TYPE_CHECKING, Any, Self +from urllib.parse import urlsplit -import httpx from buildutil import find_dev_tool, find_install_tool, logger from fastapi_vue.hostutil import parse_endpoint +if TYPE_CHECKING: + from collections.abc import Coroutine + class ProcessGroup: """Manage async subprocesses with automatic cleanup, like TaskGroup for processes.""" - def __init__(self): + def __init__(self) -> None: + """Initialize empty process tracking.""" self._procs: list[asyncio.subprocess.Process] = [] self._cmds: dict[int, str] = {} # pid -> command name async def spawn( - self, *cmd: str, cwd: str | None = None + self, + *cmd: str, + cwd: str | None = None, ) -> asyncio.subprocess.Process: """Spawn a subprocess and track it.""" cmd_name = Path(cmd[0]).stem @@ -32,7 +38,8 @@ class ProcessGroup: return proc async def wait( - self, *waitables: asyncio.subprocess.Process | Coroutine[Any, Any, Any] + self, + *waitables: asyncio.subprocess.Process | Coroutine[Any, Any, Any], ) -> None: """Wait for processes/coroutines to complete, raise SystemExit on failure.""" @@ -52,14 +59,15 @@ class ProcessGroup: logger.warning("%s failed with exit status %d", e.cmd, e.returncode) raise SystemExit(1) from None - async def __aenter__(self): + async def __aenter__(self) -> Self: + """Enter the async context manager.""" return self - async def __aexit__(self, exc_type, *_): + async def __aexit__(self, exc_type: type[BaseException] | None, *_: object) -> None: """Wait for one process to exit, terminate others, then wait for all.""" await self._cleanup(immediate=exc_type is not None) - async def _cleanup(self, immediate: bool = False): + async def _cleanup(self, *, immediate: bool = False) -> None: running = [p for p in self._procs if p.returncode is None] if not running: return @@ -87,7 +95,7 @@ class ProcessGroup: asyncio.wait_for( asyncio.gather(*[p.wait() for p in still_running]), timeout=10, - ) + ), ) except TimeoutError: for p in self._procs: @@ -97,43 +105,71 @@ class ProcessGroup: await p.wait() +async def http_get_server(url: str, timeout: float) -> str | None: # noqa: ASYNC109 + """GET url with plain asyncio streams, return the response Server header. + + Returns an empty string when the server responds without a Server header, + and None when the server is unreachable or doesn't answer in time. + """ + parts = urlsplit(url) + host = parts.hostname or "localhost" + port = parts.port or (443 if parts.scheme == "https" else 80) + path = parts.path or "/" + if parts.query: + path += f"?{parts.query}" + try: + async with asyncio.timeout(timeout): + reader, writer = await asyncio.open_connection(host, port) + try: + writer.write(f"GET {path} HTTP/1.0\r\nHost: {host}\r\n\r\n".encode()) + await writer.drain() + data = await reader.readuntil(b"\r\n\r\n") + finally: + writer.close() + except OSError, EOFError, ValueError, TimeoutError: + return None + for line in data.decode("latin-1").split("\r\n"): + if line.lower().startswith("server:"): + return line.split(":", 1)[1].strip() + return "" + + async def check_ports_free(*urls: str) -> None: """Verify URLs are not responding (ports are free). Raise SystemExit if any respond.""" - async def check(client: httpx.AsyncClient, url: str) -> None: - with suppress(httpx.RequestError): - res = await client.get(url, timeout=0.1) - server = res.headers.get("server", "server") - logger.warning("Conflicting %s already running at %s", server, url) + async def check(url: str) -> None: + server = await http_get_server(url, timeout=0.1) + if server is not None: + logger.warning( + "Conflicting %s already running at %s", server or "server", url + ) raise SystemExit(1) - async with httpx.AsyncClient() as client: - await asyncio.gather(*[check(client, url) for url in urls]) + await asyncio.gather(*[check(url) for url in urls]) -async def ready(url: str, path: str = "") -> None: +async def ready(url: str, path: str = "", max_attempts: int = 50) -> None: """Wait for the server to be ready by polling an endpoint. + Use empty path to disable the check and make this return immediately. Raises SystemExit(1) if server doesn't start in time. """ - max_attempts = 50 - full_url = f"{url}{path}" + if not path: + return - async with httpx.AsyncClient() as client: - for attempt in range(max_attempts): - try: - await client.get(full_url, timeout=1.0) - logger.info("โœ“ Backend ready!") - return - except httpx.RequestError: - if attempt == max_attempts - 1: - logger.warning("Backend didn't start in time") - raise SystemExit(1) - await asyncio.sleep(0.1) + for attempt in range(max_attempts): + if await http_get_server(f"{url}{path}", timeout=1.0) is not None: + logger.info("โœ“ Backend ready!") + return + if attempt == max_attempts - 1: + logger.warning("Backend didn't start in time") + raise SystemExit(1) + await asyncio.sleep(0.1) def setup_vite( - endpoint: str, default_port: int = 5173 + endpoint: str, + default_port: int = 5173, ) -> tuple[str, list[str], list[str]]: """Parse frontend endpoint and build commands. @@ -159,7 +195,9 @@ def setup_vite( def setup_fastapi( - endpoint: str, module: str, default_port: int = 8000 + endpoint: str, + module: str, + default_port: int = 8000, ) -> tuple[str, list[str]]: """Parse backend endpoint and build uvicorn command. @@ -174,7 +212,7 @@ def setup_fastapi( host = endpoints[0]["host"] port = endpoints[0]["port"] - reload_dir = module.split(".")[0] # Don't reload on frontend changes + reload_dir = module.split(".", maxsplit=1)[0] # Don't reload on frontend changes cmd = [ sys.executable, @@ -191,7 +229,9 @@ def setup_fastapi( def setup_cli( - cli: str, endpoint: str, default_port: int = 8000 + cli: str, + endpoint: str, + default_port: int = 8000, ) -> tuple[str, list[str]]: """Parse backend endpoint and build CLI command. @@ -207,5 +247,7 @@ def setup_cli( host = endpoints[0]["host"] port = endpoints[0]["port"] - cmd = [cli, f"--listen={host}:{port}"] + # Run the package as a module with the current interpreter, instead of + # relying on a PATH-installed CLI entry point. + cmd = [sys.executable, "-m", cli, f"--listen={host}:{port}"] return f"http://{host}:{port}", cmd -- 2.55.0 From 383c9f472e1fa67115833f3a8b694b0002dadb21 Mon Sep 17 00:00:00 2001 From: Leo Vasanko Date: Sat, 5 Sep 2026 16:06:32 +0000 Subject: [PATCH 02/48] Add public access mode (public=1) to forward auth /auth/api/forward?public=1 passes requests through with a Remote-Public header (anonymous/forbidden/authenticated) instead of 401/403, so routes can allow anonymous visitors while still identifying logged-in users. Reauth (max_age) still requires the auth flow. Documented in Headers.md, api/forward.md, Integration.md and all proxy guides. --- caddy/auth/require | 2 + docs/Headers.md | 11 +++++ docs/Integration.md | 21 +++++++++ docs/api/forward.md | 13 ++++++ docs/proxy/apisix.md | 15 ++++++- docs/proxy/caddy.md | 13 ++++++ docs/proxy/envoy.md | 11 +++++ docs/proxy/haproxy.md | 12 +++++ docs/proxy/index.md | 5 ++- docs/proxy/nginx.md | 13 ++++++ docs/proxy/traefik.md | 12 +++++ paskia/fastapi/api.py | 55 +++++++++++++++-------- paskia/fastapi/authz.py | 6 ++- tests/test_api.py | 98 +++++++++++++++++++++++++++++++++++++++++ 14 files changed, 265 insertions(+), 22 deletions(-) diff --git a/caddy/auth/require b/caddy/auth/require index 657ed3d..98f6786 100644 --- a/caddy/auth/require +++ b/caddy/auth/require @@ -2,11 +2,13 @@ # Argument is mandatory and provides a query string to /auth/api/forward # "" means just authentication # perm=yourservice:login to require specific permission +# public=1 to allow public access (backend must check Remote-Public) forward_auth {$AUTH_UPSTREAM:localhost:4401} { uri /auth/api/forward?{args[0]} header_up Connection keep-alive # Much higher performance header_up -Upgrade # Disable Upgrade: WebSocket copy_headers { + Remote-Public Remote-User Remote-Name Remote-Groups diff --git a/docs/Headers.md b/docs/Headers.md index 6ff75eb..6c669b0 100644 --- a/docs/Headers.md +++ b/docs/Headers.md @@ -13,6 +13,17 @@ | Remote-Groups | Permissions the user has, comma separated | **auth:admin,yourapp:reports** | | Remote-Session-Expires | Session expiry timestamp (ISO 8601 UTC) | **2030-12-31T23:59:59Z** | | Remote-Credential | Credential UUID | Identifier for the sign-in passkey (string) | +| Remote-Public | Public-access marker, only present on routes using [`public=1`](api/forward.md#public-access) | **authenticated**, **forbidden** or **anonymous** | + +### Public access + +On routes configured with `public=1`, every forwarded request carries `Remote-Public` and the backend must check it before treating the request as authorized: + +- `authenticated` โ€” the user has everything the route asked for; full `Remote-*` headers. +- `forbidden` โ€” the user is logged in but the route's `perm` check failed. Full identity headers are sent, including `Remote-Groups` โ€” it is trustworthy, it just lacks the requested permission. +- `anonymous` โ€” no valid session; no identity headers are sent. + +Without `public=1` the header is absent and every request reaching the backend is fully authorized. Similar headers are also used by other authentication systems like [Authelia](https://www.authelia.com/integration/trusted-header-sso/introduction/) to signal the backend application information about the signed in user. diff --git a/docs/Integration.md b/docs/Integration.md index 65c0c22..b531554 100644 --- a/docs/Integration.md +++ b/docs/Integration.md @@ -132,6 +132,27 @@ Be sure to REMOVE connection hop-by-hop headers (these will break WebSockets amo "Connection", "Keep-Alive", "Proxy-Connection", "TE", "Transfer-Encoding", "Upgrade" ``` +## Public access + +For apps where authentication is optional, configure the proxy route with `public=1` (see your [proxy guide](proxy/index.md)). The auth check then always lets the request through, and your backend branches on the `Remote-Public` header: + +- `anonymous` โ€” no valid session; no `Remote-*` identity headers are present. +- `forbidden` โ€” the user is logged in (identity headers are present and trustworthy) but the route's `perm` was not granted. +- `authenticated` โ€” session valid and all requested permissions met. + +```python +# Example: Python/FastAPI +@app.get("/api/reports") +def reports(request: Request): + public = request.headers.get("Remote-Public") + if public != "authenticated": + raise HTTPException(401) # or serve a limited public view + user_id = request.headers.get("Remote-User") + # ... +``` + +Login-on-demand still works unchanged: any 401 your app itself returns for privileged operations carries the `auth.iframe` URL that the [paskia](https://www.npmjs.com/package/paskia) module handles automatically (see [API Fetch with Automatic Auth](#api-fetch-with-automatic-auth)). A `max_age` reauth requirement on the route still returns the 401 auth flow directly from the proxy. See [public access](api/forward.md#public-access) and [Headers](Headers.md#public-access). + ## Proxying /auth/ to Paskia Your app server needs to proxy `/auth/` paths to Paskia. This can be done by your application but is much easier done by a reverse proxy. The [Forward-Auth Proxy Guides](proxy/index.md) cover Caddy, Nginx, Traefik, Apache APISIX, Envoy and HAProxy. diff --git a/docs/api/forward.md b/docs/api/forward.md index f4ddf07..c89da94 100644 --- a/docs/api/forward.md +++ b/docs/api/forward.md @@ -15,6 +15,19 @@ See [Forward-Auth Proxy Guides](../proxy/index.md) for Caddy, Nginx, Traefik, Ap |-----------|-------------| | perm | Required permissions. See the [perm argument](perm.md). | | max_age | Require recent passkey use. See the [max_age argument](max-age.md). | +| public | `public=1` allows public access: instead of 401 (no/expired session) or 403 (permission denied), the request passes with a `Remote-Public` header marking the bypass. Reauth (`max_age`) still requires the auth flow. | + +## Public access + +With `public=1` the endpoint returns 204 in every case except reauth and malformed arguments, and always sets `Remote-Public`: + +| Value | Meaning | Identity headers | +|---|---|---| +| `authenticated` | Session valid, all requested permissions met | Full `Remote-*` set | +| `forbidden` | Session valid, but the `perm` check failed | Full `Remote-*` set (including `Remote-Groups` โ€” it is trustworthy, it just lacks the requested permission) | +| `anonymous` | No valid session | None | + +The backend must check `Remote-Public` before treating the request as authorized. See [Trusted Headers](../Headers.md) and the "Public access" section in the [proxy guides](../proxy/index.md). ## Request headers diff --git a/docs/proxy/apisix.md b/docs/proxy/apisix.md index e1e7b9d..5361952 100644 --- a/docs/proxy/apisix.md +++ b/docs/proxy/apisix.md @@ -54,7 +54,8 @@ curl "http://127.0.0.1:9180/apisix/admin/routes" -X PUT \ "Remote-Role", "Remote-Role-Name", "Remote-Session-Expires", - "Remote-Credential" + "Remote-Credential", + "Remote-Public" ] } }, @@ -110,6 +111,7 @@ services: - Remote-Role-Name - Remote-Session-Expires - Remote-Credential + - Remote-Public upstream: type: roundrobin nodes: @@ -156,6 +158,17 @@ uri: http://localhost:4401/auth/api/forward The last form requires only authentication. See [perm argument](../api/perm.md) and [max_age argument](../api/max-age.md). +## Public access + +For routes where anonymous visitors are allowed but logged-in users should still be identified, add `public=1` to the `forward-auth` URI: + +```yaml +uri: http://localhost:4401/auth/api/forward?public=1 +uri: http://localhost:4401/auth/api/forward?public=1&perm=myapp:reports +``` + +The auth check then always returns 204 (except reauth with `max_age`, which still returns the 401 auth flow), and the `Remote-Public` header โ€” included in the `upstream_headers` lists above โ€” marks each request as `anonymous`, `forbidden` or `authenticated`. The backend always runs and must check `Remote-Public` before treating the request as authorized. See [public access](../api/forward.md#public-access) and [trusted headers](../Headers.md#public-access). + ## Notes - The auth request is `GET` by default. Since the `forward-auth` plugin does not forward the request body unless `request_method` is set to `POST`, the default `GET` is the right choice for Paskia. diff --git a/docs/proxy/caddy.md b/docs/proxy/caddy.md index 1d8792b..bab71c2 100644 --- a/docs/proxy/caddy.md +++ b/docs/proxy/caddy.md @@ -58,6 +58,19 @@ app.example.com { The above setup allows unauthenticated access to certain files, then implements two different access controls for your backend app depending on which path is accessed. Note that the perm and max-age options may be combined, e.g. `perm=myapp:admin&max-age=5min` on a very sensitive endpoint. This will require additional authentication if the passkey hasn't been used in the last 5 minutes (automatic session renewals don't affect this). Use `""` if you only want the user to be authenticated with no time or perm requirements. +### Public access (public=1) + +For routes where anonymous visitors are allowed but logged-in users should still be identified, add `public=1` to the same snippet: + +```caddyfile +handle { + import auth/require "public=1" + reverse_proxy :3000 +} +``` + +The auth check then always passes (204): anonymous requests and users lacking a requested `perm` reach your backend marked with a `Remote-Public` header (`anonymous`, `forbidden` or `authenticated`) instead of getting a 401/403. Your backend must check `Remote-Public` before treating the request as authorized โ€” see [trusted headers](../Headers.md#public-access). A `max_age` reauth requirement still renders the authentication page, even on public routes. + ### Dedicated Authentication Site When you setup a separate subdomain for the authentication site, just add to your config another section for the auth host: diff --git a/docs/proxy/envoy.md b/docs/proxy/envoy.md index df317c7..e409103 100644 --- a/docs/proxy/envoy.md +++ b/docs/proxy/envoy.md @@ -163,6 +163,17 @@ See [perm argument](../api/perm.md) and [max_age argument](../api/max-age.md) fo If you use a dedicated authentication host (`--auth-host`), route `auth.example.com` to the Paskia cluster and you do not need the `/auth/` bypass above. Otherwise, make sure the `/auth/` route keeps the `Upgrade` and `Connection` headers so passkey WebSocket endpoints work. The default Envoy router handles `Upgrade` headers when the client requests them. +## Public access + +For routes where anonymous visitors are allowed but logged-in users should still be identified, add `public=1` to `path_override` (globally or per route): + +```yaml +path_override: "/auth/api/forward?public=1" +path_override: "/auth/api/forward?public=1&perm=myapp:reports" +``` + +The auth check then always returns 204 (except reauth with `max_age`, which still returns the 401 auth flow), and the `Remote-Public` header โ€” matched by the `prefix: Remote-` rule in `allowed_upstream_headers` โ€” marks each request as `anonymous`, `forbidden` or `authenticated`. The backend always runs and must check `Remote-Public` before treating the request as authorized. See [public access](../api/forward.md#public-access) and [trusted headers](../Headers.md#public-access). + ## Notes - Envoy's `ext_authz` filter does not send the request body to the auth server by default. For Paskia this is fine. diff --git a/docs/proxy/haproxy.md b/docs/proxy/haproxy.md index e235495..39f0156 100644 --- a/docs/proxy/haproxy.md +++ b/docs/proxy/haproxy.md @@ -106,6 +106,18 @@ frontend app See [perm argument](../api/perm.md) and [max_age argument](../api/max-age.md) for query parameter syntax. +## Public access + +For routes where anonymous visitors are allowed but logged-in users should still be identified, add `public=1` to the auth subrequest path: + +```haproxy +http-request lua.auth-intercept paskia_auth /auth/api/forward?public=1 GET Host,Cookie,Accept,X-Forwarded-Method,X-Forwarded-Uri Remote-* * +# or with a permission the backend will check itself: +http-request lua.auth-intercept paskia_auth /auth/api/forward?public=1&perm=myapp:reports GET Host,Cookie,Accept,X-Forwarded-Method,X-Forwarded-Uri Remote-* * +``` + +The `Remote-*` success-headers glob already copies the `Remote-Public` header that marks each request as `anonymous`, `forbidden` or `authenticated`. With `public=1` the backend always runs and must check `Remote-Public` before treating the request as authorized; only reauth (`max_age`) still returns the 401 auth flow, so the `http-request deny` safety net simply never triggers on public routes. See [public access](../api/forward.md#public-access) and [trusted headers](../Headers.md#public-access). + ## Notes - The Lua script strips the request body from the auth subrequest, so Paskia's `/auth/api/forward` will only see the headers. diff --git a/docs/proxy/index.md b/docs/proxy/index.md index 1a420c4..84cd3b4 100644 --- a/docs/proxy/index.md +++ b/docs/proxy/index.md @@ -23,6 +23,7 @@ No matter which proxy you use, the auth subrequest must: 2. Include the query parameters Paskia needs for access control: - `perm` โ€” required permission scope, repeatable (e.g. `perm=myapp:login`). See [perm argument](../api/perm.md). - `max_age` โ€” how recently the user must have authenticated (e.g. `max_age=5min`). See [max_age argument](../api/max-age.md). + - `public=1` โ€” optional; allow public access (anonymous visitors and users missing `perm` pass through, marked with a `Remote-Public` header instead of a 401/403). See [public access](../api/forward.md#public-access). 3. Forward these request headers from the original client request: - `Host` โ€” the site the user is visiting. - `Cookie` โ€” the session cookie, normally `__Host-paskia`. @@ -30,8 +31,8 @@ No matter which proxy you use, the auth subrequest must: - `X-Forwarded-Uri` โ€” the original path and query string (e.g. `/reports?foo=bar`). - `Accept` โ€” decides whether a 401/403 response should be HTML (browser) or JSON (API/fetch). 4. Strip hop-by-hop headers (`Connection`, `Upgrade`, `Transfer-Encoding`, `Keep-Alive`, `Proxy-Connection`, `TE`) from the auth subrequest. The auth check is a plain HTTP request and must not carry WebSocket/body framing headers. -5. On a `204 No Content` response, copy the `Remote-*` response headers to the request that is forwarded to the protected backend. The headers are the whole point of the auth check. -6. On a 401/403 response, send Paskia's response back to the client without contacting the protected backend. +5. On a `204 No Content` response, copy the `Remote-*` response headers to the request that is forwarded to the protected backend. The headers are the whole point of the auth check. With `public=1`, also copy `Remote-Public` โ€” it marks whether the request is `authenticated`, `forbidden` or `anonymous`, and the backend must check it. +6. On a 401/403 response, send Paskia's response back to the client without contacting the protected backend. (With `public=1` these only occur for reauth requirements.) 7. Also proxy the `/auth/` path prefix to Paskia so the login/profile UI, API endpoints, and WebSockets are reachable. Paskia's WebSocket endpoints need `Upgrade` and `Connection` headers passed through for that path. ## Backend usage diff --git a/docs/proxy/nginx.md b/docs/proxy/nginx.md index 9619481..1052011 100644 --- a/docs/proxy/nginx.md +++ b/docs/proxy/nginx.md @@ -35,6 +35,7 @@ server { auth_request_set $remote_role_name $upstream_http_remote_role_name; auth_request_set $remote_session_exp $upstream_http_remote_session_expires; auth_request_set $remote_credential $upstream_http_remote_credential; + auth_request_set $remote_public $upstream_http_remote_public; proxy_set_header Remote-User $remote_user; proxy_set_header Remote-Name $remote_name; @@ -45,6 +46,7 @@ server { proxy_set_header Remote-Role-Name $remote_role_name; proxy_set_header Remote-Session-Expires $remote_session_exp; proxy_set_header Remote-Credential $remote_credential; + proxy_set_header Remote-Public $remote_public; # 4. The proxy_set_header lines above override any client-supplied # Remote-* headers, so the backend receives only the values from @@ -123,6 +125,17 @@ location /static/ { } ``` +## Public access + +For routes where anonymous visitors are allowed but logged-in users should still be identified, add `public=1` to the auth subrequest URI inside `/auth-internal`: + +```nginx +proxy_pass http://localhost:4401/auth/api/forward?public=1; +proxy_pass http://localhost:4401/auth/api/forward?public=1&perm=myapp:reports; +``` + +The auth check then always returns 204 (except reauth with `max_age`, which still returns the 401 auth flow), and `Remote-Public` marks each request as `anonymous`, `forbidden` or `authenticated`. It is captured and forwarded by the `auth_request_set $remote_public` / `proxy_set_header Remote-Public` lines added in the overview above โ€” the backend always runs and must check `Remote-Public` before treating the request as authorized. See [public access](../api/forward.md#public-access) and [trusted headers](../Headers.md#public-access). + ## Notes - Nginx `auth_request` always makes the auth subrequest with the same HTTP method as the original request, but the body is suppressed by the configuration above. Paskia uses the `X-Forwarded-Method` and `X-Forwarded-Uri` headers for logging. diff --git a/docs/proxy/traefik.md b/docs/proxy/traefik.md index 7b4ef29..180c0d8 100644 --- a/docs/proxy/traefik.md +++ b/docs/proxy/traefik.md @@ -85,6 +85,7 @@ authResponseHeaders: - Remote-Role-Name - Remote-Session-Expires - Remote-Credential + - Remote-Public ``` ## Proxying `/auth/` to Paskia @@ -119,6 +120,17 @@ labels: - "traefik.http.middlewares.paskia-auth.forwardauth.authRequestHeaders=Host,Cookie,Accept,X-Forwarded-Method,X-Forwarded-Uri" ``` +## Public access + +For routes where anonymous visitors are allowed but logged-in users should still be identified, add `public=1` to the middleware `address`: + +```yaml +address: "http://localhost:4401/auth/api/forward?public=1" +address: "http://localhost:4401/auth/api/forward?public=1&perm=myapp:reports" +``` + +The auth check then always returns 204 (except reauth with `max_age`, which still returns the 401 auth flow), and the `Remote-Public` header โ€” copied by `authResponseHeadersRegex: "^Remote-"` โ€” marks each request as `anonymous`, `forbidden` or `authenticated`. The backend always runs and must check `Remote-Public` before treating the request as authorized. See [public access](../api/forward.md#public-access) and [trusted headers](../Headers.md#public-access). + ## Notes - By default ForwardAuth sends a request without the original body. If you need to forward the body for logging/validation, set `forwardBody: true` and a sensible `maxBodySize`, but for Paskia this is not required. diff --git a/paskia/fastapi/api.py b/paskia/fastapi/api.py index b3b155a..9e3c3ee 100644 --- a/paskia/fastapi/api.py +++ b/paskia/fastapi/api.py @@ -198,12 +198,31 @@ async def check_user( return MsgspecResponse(ApiCheckUserResponse(valid=valid, ctx=ctx)) +def _remote_headers(ctx) -> dict[str, str]: + """Build the Remote-* identity headers for a verified session context.""" + role_permissions = {p.scope for p in ctx.permissions} if ctx.permissions else set() + return { + "Remote-User": str(ctx.user.uuid), + "Remote-Name": ctx.user.display_name, + "Remote-Groups": ",".join(sorted(role_permissions)), + "Remote-Org": str(ctx.org.uuid), + "Remote-Org-Name": ctx.org.display_name, + "Remote-Role": str(ctx.role.uuid), + "Remote-Role-Name": ctx.role.display_name, + "Remote-Session-Expires": ( + (ctx.session.validated + EXPIRES).isoformat().replace("+00:00", "Z") + ), + "Remote-Credential": str(ctx.session.credential), + } + + @app.get("/forward") async def forward_authentication( request: Request, response: Response, perm: list[str] = Query([]), max_age: str | None = Query(None), + public: bool = Query(False), auth=AUTH_COOKIE, ): """Forward auth validation for Caddy/Nginx. @@ -213,6 +232,11 @@ async def forward_authentication( required; separate alternatives with '|' for OR semantics within a group). - max_age: maximum age of authentication (e.g., "5m", "1h", "30s"). If the session is older than this, user must re-authenticate. + - public: allow public access โ€” instead of 401 (no/expired session) or 403 + (permission denied), return 204 with a Remote-Public header + (anonymous/forbidden) so the backend can decide. Reauth (max_age) + still requires the auth flow. Successful checks are marked + Remote-Public: authenticated. Success: 204 No Content with Remote-* headers describing the authenticated user. Failure (unauthenticated / unauthorized): 4xx response. @@ -245,26 +269,21 @@ async def forward_authentication( max_age=max_age, ) _set_log_extra(request, forwarded, ctx.session.key) - # Build permission scopes for Remote-Groups header - role_permissions = ( - {p.scope for p in ctx.permissions} if ctx.permissions else set() - ) - - remote_headers: dict[str, str] = { - "Remote-User": str(ctx.user.uuid), - "Remote-Name": ctx.user.display_name, - "Remote-Groups": ",".join(sorted(role_permissions)), - "Remote-Org": str(ctx.org.uuid), - "Remote-Org-Name": ctx.org.display_name, - "Remote-Role": str(ctx.role.uuid), - "Remote-Role-Name": ctx.role.display_name, - "Remote-Session-Expires": ( - (ctx.session.validated + EXPIRES).isoformat().replace("+00:00", "Z") - ), - "Remote-Credential": str(ctx.session.credential), - } + remote_headers = _remote_headers(ctx) + if public: + remote_headers["Remote-Public"] = "authenticated" return Response(status_code=204, headers=remote_headers) except authz.AuthException as e: + # Public access: pass the request through instead of an auth flow. + # Reauth is never soft-passed: an authenticated user was explicitly asked + # for fresh verification (log out first to use the public mode). + if public and e.mode in ("login", "forbidden"): + _set_log_extra(request, forwarded, f"public:{e.mode}") + if e.mode == "forbidden" and e.ctx is not None: + headers = {**_remote_headers(e.ctx), "Remote-Public": "forbidden"} + else: + headers = {"Remote-Public": "anonymous"} + return Response(status_code=204, headers=headers) # Clear cookie only if session is invalid (not for reauth) if e.clear_session: session.clear_session_cookie(response) diff --git a/paskia/fastapi/authz.py b/paskia/fastapi/authz.py index 97c55ca..71cec70 100644 --- a/paskia/fastapi/authz.py +++ b/paskia/fastapi/authz.py @@ -15,9 +15,10 @@ class AuthException(HTTPException): Attributes: status_code: HTTP status code (401 for auth, 403 for authz) detail: Error message - mode: UI mode ('login' or 'reauth') + mode: UI mode ('login', 'reauth' or 'forbidden') clear_session: Whether to clear the session cookie (True for invalid sessions) metadata: Additional data to pass to the frontend + ctx: Session context, set only for 403 (session valid, permission missing) """ def __init__( @@ -26,11 +27,13 @@ class AuthException(HTTPException): detail: str, mode: str, clear_session: bool = False, + ctx=None, **metadata, ): super().__init__(status_code=status_code, detail=detail) self.mode = mode self.clear_session = clear_session + self.ctx = ctx self.metadata = metadata @@ -108,6 +111,7 @@ async def verify( status_code=403, mode="forbidden", detail="Permission required", + ctx=ctx, theme=user_theme, ) diff --git a/tests/test_api.py b/tests/test_api.py index 1aa2d87..70cd10b 100644 --- a/tests/test_api.py +++ b/tests/test_api.py @@ -235,6 +235,104 @@ class TestForwardEndpoint: assert data["auth"]["mode"] == "forbidden" +class TestForwardPublicAccess: + """Tests for GET /auth/api/forward with public=1 (public access mode)""" + + @pytest.mark.asyncio + async def test_public_without_session_returns_204_anonymous( + self, client: httpx.AsyncClient + ): + """Public access without session should pass as anonymous.""" + response = await client.get("/auth/api/forward?public=1") + assert response.status_code == 204 + assert response.headers["Remote-Public"] == "anonymous" + assert "Remote-User" not in response.headers + assert "Remote-Groups" not in response.headers + + @pytest.mark.asyncio + async def test_public_with_expired_session_returns_204_anonymous( + self, client: httpx.AsyncClient + ): + """Public access with invalid session should pass as anonymous.""" + fake_token = "aaaaaaaaaaaaaaaa" # Exactly 16 characters + response = await client.get( + "/auth/api/forward?public=1", + headers={**auth_headers(fake_token), "Host": "localhost:4401"}, + ) + assert response.status_code == 204 + assert response.headers["Remote-Public"] == "anonymous" + assert "Remote-User" not in response.headers + # Cookie must not be cleared on public pass-through + assert "set-cookie" not in response.headers + + @pytest.mark.asyncio + async def test_public_permission_denied_returns_204_forbidden( + self, client: httpx.AsyncClient, regular_session_token: str + ): + """Public access with missing permission should pass as forbidden with identity.""" + response = await client.get( + "/auth/api/forward?public=1&perm=auth:admin", + headers={ + **auth_headers(regular_session_token), + "Host": "localhost:4401", + }, + ) + assert response.status_code == 204 + assert response.headers["Remote-Public"] == "forbidden" + # Identity is known and sent, including (trustworthy) groups + assert "Remote-User" in response.headers + assert "Remote-Groups" in response.headers + + @pytest.mark.asyncio + async def test_public_authorized_returns_204_authenticated( + self, client: httpx.AsyncClient, session_token: str + ): + """Public access with full authorization should be marked authenticated.""" + response = await client.get( + "/auth/api/forward?public=1&perm=auth:admin", + headers={**auth_headers(session_token), "Host": "localhost:4401"}, + ) + assert response.status_code == 204 + assert response.headers["Remote-Public"] == "authenticated" + assert "Remote-User" in response.headers + assert "Remote-Groups" in response.headers + + @pytest.mark.asyncio + async def test_public_reauth_still_returns_401( + self, client: httpx.AsyncClient, session_token: str + ): + """Reauth (max_age) is never soft-passed, even with public=1.""" + response = await client.get( + "/auth/api/forward?public=1&max_age=0s", + headers={ + **auth_headers(session_token), + "Host": "localhost:4401", + "Accept": "application/json", + }, + ) + assert response.status_code == 401 + data = response.json() + assert data["auth"]["mode"] == "reauth" + + @pytest.mark.asyncio + async def test_public_malformed_perm_returns_400(self, client: httpx.AsyncClient): + """Malformed perm remains a hard error with public=1.""" + response = await client.get("/auth/api/forward?public=1&perm=a||b") + assert response.status_code == 400 + + @pytest.mark.asyncio + async def test_without_public_no_remote_public_header( + self, client: httpx.AsyncClient, session_token: str + ): + """Without public=1, Remote-Public is absent on success.""" + response = await client.get( + "/auth/api/forward", + headers={**auth_headers(session_token), "Host": "localhost:4401"}, + ) + assert response.status_code == 204 + assert "Remote-Public" not in response.headers + + class TestPermOrSemantics: """Tests for OR ('|') semantics and strict parsing of the perm argument""" -- 2.55.0 From 2da1ce777af381a8d093400c0d19d2a4f4d517fb Mon Sep 17 00:00:00 2001 From: Leo Vasanko Date: Sun, 6 Sep 2026 03:19:42 +0000 Subject: [PATCH 03/48] Multi-site plan v4: combined paskia.kantadb, bootstrap-only CLI, runtime realm management --- docs/MultiSite.md | 741 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 741 insertions(+) create mode 100644 docs/MultiSite.md diff --git a/docs/MultiSite.md b/docs/MultiSite.md new file mode 100644 index 0000000..1f8efb2 --- /dev/null +++ b/docs/MultiSite.md @@ -0,0 +1,741 @@ +# Multi-Site Support: Combined-Database Plan + +Status: **draft v4 for review** โ€” no code changes made. v4 folds in a +simplification round: Related Origin Requests are now assumed to have +**universal browser support** (Firefox included); there are **no existing +multi-database deployments** to migrate โ€” the only legacy path is adopting +a lone `.paskiadb` into the new combined `paskia.kantadb` file; and +realm configuration is **bootstrap-only on the CLI** โ€” rp-ids, rp-names, +origins and auth hosts are managed at runtime through the master-admin web +interface, so the serve command takes no realm arguments at all. + +Goal: one paskia process on one port (4401) serves multiple sites with +**one combined database**. The _administrative instance_ is separated from +the _WebAuthn RP_: organizations and users are global across rp-ids; +rp-id becomes a first-class per-realm object; passkeys remain tied to +their rp-id (WebAuthn-enforced); sessions remain host-bound exactly as +today. Motivating case: `app1.company.com` and `app2.com` cannot share an +rp-id, but user management must be under single common controls. + +Decisions already made (from review rounds): + +- **One combined database** at a fixed CWD-relative path: + **`paskia.kantadb`** (a single kanta JSONL file). No `PASKIA_DB`, no + per-rp-id directories, no directory scanning. The `paskiadb`/`main.db` + names are retired (ยง10). +- **CLI is bootstrap-only**: `paskia init` seeds the database with the + initial realm(s); plain `paskia` opens `paskia.kantadb` and serves + whatever realms are stored. rp-id no longer selects which database to + open, which removes the whole class of CLI/runtime mixups. +- **Runtime realm management via the admin interface**: adding rp-ids, + changing rp-names, origins and auth hosts are master-admin operations + (ยง9), exactly like rp-name changes work today after first setup. The + admin interface is shared across the whole instance โ€” as long as a + master admin can log in on some host, all further configuration happens + there. +- Cross-rp-id logins are **permitted** (ยง2 mechanisms); no separate + per-site user silos. + +--- + +## 1. What is global vs. per-realm + +**Global (single instance, shared across realms):** + +| Data | Notes | +| ------------------------------- | ----------------------------------------------------------------------- | +| Organizations, Roles, Users | already global structs; unchanged | +| Permissions | `domain` field already host-scopes effectiveness (`structs.py:704-706`) | +| Sessions | already host-bound (`Session.host`, exact match `structs.py:678-682`) | +| Credentials/passkeys | global collection, each stamped with its `rp_id` (ยง4) | +| Reset tokens | user-bound; global | +| Avatars | `users//profile.webp` under the one user-files root (ยง10) | +| Auth codes, remote-auth manager | in-memory; gain rp-id fields (ยง7) | + +**Per-realm (registry, keyed by rp-id):** + +| Data | Notes | +| -------------------------------------- | --------------------------------------------------------------- | +| `rp_id`, `rp_name`, origins, auth_host | stored combined `Config` (ยง3) | +| `Passkey` instance | per rp-id; ceremonies verify against the _origin realm's_ rp-id | +| `site_url`/`site_path` | runtime derivation, per realm | +| OIDC provider (keys, clients) | per rp-id โ€” each realm is an independent issuer (ยง8) | + +Terminology: a **realm** is one rp-id with its associated hosts and +origins (the feedback's "authentication realm"). A **site** is any host +served by the instance; each host belongs to exactly one realm. The +_administrative instance_ is the whole process: global users/orgs, N +realms. + +The key simplification: `db.data()` stays a plain global singleton. The +contextvar is needed only for the **current realm** (passkey, config, +OIDC view) โ€” not for database access. + +## 2. Login architecture: three composable mechanisms + +The plan implements the realm infrastructure (ยง3-ยง9) once, plus three +mechanisms that share it. They are alternatives _per deployment_, and +composable within one instance. + +### 2.A WebAuthn Related Origin Requests (preferred for trusted domain families) + +WebAuthn Level 3 lets otherwise-unrelated domains share one rp-id: the +canonical RP publishes `/.well-known/webauthn` listing permitted origins, +and those origins may then run ceremonies with the common rp-id locally โ€” +no redirects, no cross-domain cookies. Browser support is now universal +(Firefox included), so ROR needs no fallback mechanism for browser +reasons. + +Model: realm `company.com` with related origin `https://app2.com`. A page +on `app2.com` calls WebAuthn with `rpId: "company.com"`; the passkey is +scoped to `company.com`; `clientDataJSON.origin` is `https://app2.com`, +which the backend validates against the realm's allow-list. + +Server-side feasibility (verified against the installed `webauthn` 3.0.0): +paskia's `Passkey` passes `expected_origin=` +and `expected_rp_id=self.rp_id` (`sansio.py:188-193,255-263`); the +library string-compares origin and rp-id separately. The frontend never +chooses `rpId` client-side โ€” ceremony options arrive from the server over +the WS (`frontend/src/utils/passkey.js:40,68`). So the change set is: + +- `Passkey._validate_origin` (`sansio.py:95-106`) currently requires + origin == rp-id or subdomain. New rule: an origin is valid if it is in + the rp-id subtree **or explicitly listed in the realm's configured + origins**. Explicit listing becomes the trust boundary โ€” exactly the + right semantics, since `allowed_origins` is already an allow-list. + (Today's semantics are subtree-AND-listed when a list exists; the new + subtree-OR-listed is additive-only, so existing configs keep passing.) +- **Remove the redundant inline origin gate** in `authenticate_and_login` + (`wschat.py:93-95` re-implements `hostname == rp_id or endswith`) โ€” it + would reject related origins after `validate_origin` accepted them. + Dispatch already resolved the realm from the Origin; the endpoint-side + `validate_origin` is the single origin rule. +- New endpoint: `GET /.well-known/webauthn` on the canonical rp-id host, + serving `{"origins": ["https://app2.com", ...]}` from the realm's + configured non-subdomain origins. +- Dispatch resolution gains a rule: a Host matching a configured + related-origin hostname resolves to that origin's realm (exact match + only โ€” `www.app2.com` does not follow `app2.com`; document this). + +Deployment constraint (documented in ยง15): the **browser** fetches +`https:///.well-known/webauthn` from the canonical apex directly โ€” +if paskia does not host the apex, the JSON must be published there +statically. + +Constraints and warnings (from the WebAuthn WG, to be documented): +implementations must support at least **5 registrable origin labels** and +may cap more aggressively โ€” this is for a small family of same-trust +domains, not hundreds of customer domains. Sharing an rp-id merges the +security boundary: a weakly protected marketing domain should not share +the realm of the admin application. Config validation enforces a +configurable cap (default 5) on related origins per realm. + +**Re-enrollment note**: passkeys never move between rp-ids +(WebAuthn-enforced). A host family that first deploys separate realms +(2.B) and later consolidates to Related Origins re-enrolls: authenticate +against the old realm (or via 2.C), register a new credential under the +common rp-id, retire the old one. The UI's per-credential rp-id badge +(ยง9) makes this visible. No automated credential migration is provided or +needed. + +### 2.B Multiple rp-id realms under one administrative instance (the base refactor) + +For domains that should _not_ share an rp-id: rp-id is a first-class +object (realm), not an instance attribute. Users are global identities; +credentials carry `rp_id`: + +``` +Instance +โ”œโ”€โ”€ Orgs / Roles / Users (global) +โ””โ”€โ”€ Realms + โ”œโ”€โ”€ company.com (origins [...], credentials scoped by rp_id) + โ”œโ”€โ”€ app2.com (origins [...], credentials scoped by rp_id) + โ””โ”€โ”€ customer.net (origins [...], credentials scoped by rp_id) +``` + +Alice can hold both a `company.com` and an `app2.com` passkey; sessions +stay host-only. This is the refactor described in ยง3-ยง9 and is worthwhile +**regardless of which login mechanism a deployment uses** โ€” 2.A is +implemented as "a realm may declare extra origins", 2.C as "a realm may +be entered via remote authorization". + +**Deferred idea from the feedback โ€” an Identity layer above the +org-owned User** (`Identity โ†’ N org memberships + N credentials`). Not +part of this plan: the current `User โ†’ Role โ†’ Org` ownership +(`structs.py:198-286`) is deeply embedded (bootstrap, admin API, +permissions), and multi-site works without it. We do adopt the feedback's +architectural rule now: **authentication establishes identity, not +organization** โ€” the requested hostname selects the org/permission +context after authentication (already true via `Permission.domain` +host-scoping and session host binding). A future Identity split should +preserve that rule. + +### 2.C Remote authorization + opportunistic local enrollment (bootstrap/recovery path) + +For a realm where the user has no credential, the existing remote-login +mechanism already provides a federation-style flow: unauthenticated device +requests, authenticated device permits, a short-lived **single-use opaque +exchange code** (60s `CookieCode`, `authcode.py`) is redeemed by the +requesting host, which sets its own host-only cookie. No shared cookies, +no reusable tokens in URLs โ€” matching the feedback's +authorization-code-shaped recommendation; the two channels (WS pairing +code vs redirect with `state`) are UX variants over the same code +redemption primitive. + +Changes under this plan: + +- Cross-realm permits are **allowed** (ยง7.2): a device authenticated at + `company.com` may authorize a session for `app2.com`; the request's + realm is recorded and shown to the approver; the target host is + registry-validated. +- **Same-device redirect variant** (optional, closes open question from + v1): "logged in at the auth host, bounce to the app host with a code" โ€” + reuse the same `CookieCode` machinery with a `redirect_uri`+`state` + parameter set, PKCE not needed server-to-self but `state` protects the + redirect leg. This is a small addition over ยง7.1, kept as an optional + follow-up. +- **Opportunistic local enrollment**: after a cross-realm remote login, + the UI offers "Add a passkey for faster login here". The mechanism + already exists โ€” the remote flow's `register` action issues a + `device addition` reset token (`remote.py:325-333`) and registration + runs locally under the new realm's rp-id, stamping `Credential.rp_id` + (ยง4). This makes remote login primarily bootstrap/recovery, while + everyday authentication stays local. + +### Policy summary (how deployments choose) + +| Situation | Mechanism | +| -------------------------------------------------- | --------------------------------------------- | +| Few closely related, equally trusted brand domains | 2.A Related Origins โ€” one passkey | +| Independent / customer / lower-trust domains | 2.B separate realms โ€” passkey per realm | +| User lacks a credential for the current realm | 2.C remote authorization, then enroll locally | + +## 3. Configuration model + +### 3.1 Stored config (breaking change) + +```python +class RealmConfig(msgspec.Struct, omit_defaults=True): + rp_id: str + rp_name: str | None = None + auth_host: str | None = None # this realm's dedicated auth host + origins: list[str] | None = None # subdomain origins AND related origins (ยง2.A) + +class Config(msgspec.Struct, omit_defaults=True): + realms: list[RealmConfig] # at least one; first entry is the default realm + listen: list[str] | None = None # process-global +``` + +- Old top-level `rp_id/rp_name/auth_host/origins` fields removed; a kanta + migration converts existing databases (ยง10). Default constructors move + to the new shape everywhere: `structs.py:622` (DB.config factory), + `operations.py:40` (sentinel), `db/bootstrap.py:148`. +- "At least one realm" is not expressible in msgspec โ€” enforce it in a + startup/validation check. +- First entry is the default realm, used only where a default is genuinely + needed (bootstrap reset-link URL, startup box ordering, master-admin + entry point) โ€” never for dispatch. +- **Origin validation**: each configured origin is either in the rp-id + subtree (classic) or an explicit related origin (ยง2.A). Related origins + are counted and capped (default 5 registrable labels per realm) and + must not collide with another realm's rp-id/auth-host/related origins. + These rules are enforced **both at startup and at admin write time** + (ยง9) โ€” startup-only checks are bypassable at runtime. Origins are never + _implicitly_ cross-domain. + +### 3.2 CLI: bootstrap (`paskia init`) vs. serve (`paskia`) + +The CLI is split so that realm options exist only at bootstrap time โ€” +they can never mix with runtime configuration of an already-configured +instance: + +- **`paskia init`** โ€” creates `paskia.kantadb` in CWD and seeds it: + - `--rp-id`: repeatable/comma-separated, default `["localhost"]`; + normalized, deduped. Multiple values create multiple realms at once + (useful for devserver/e2e); the **first is the default realm**. + - `--rp-name`: single value, applies to the default realm. Its purpose + is that the very first admin registration ceremony already shows the + correct RP name; afterwards rp-names are edited via the admin + interface (ยง9), as are any additional realms' names. + - `--auth-host`, `--origin`: apply to the default realm; existing + normalization (`validate_auth_host`, `normalize_origin`, + `normalize_auth_host_and_origins`) reused. Further realms' hosts are + configured via the admin interface. + - `--listen`: stored into `Config.listen` (process-global). + - Runs the kanta bootstrap (admin user + registration reset link, link + URL from the default realm) and prints the link. Refuses to run if + `paskia.kantadb` already exists, or if an un-adopted legacy + `*.paskiadb` is present (ยง10 โ€” serve must adopt it first). +- **`paskia`** โ€” serve. Takes **no realm options**; only `--listen` + (per-run override of stored `Config.listen`, never persisted) and + dev/debug flags. Startup flow: legacy-adoption pre-flight (ยง10) โ†’ open + `paskia.kantadb` โ†’ validate the stored realm set cross-realm (rp-ids + distinct; auth hosts distinct from each other and from every rp-id; + related origins capped and collision-free) โ†’ build the realm registry + (ยง5) โ†’ serve. Missing database โ†’ startup error pointing at + `paskia init`. +- `--save` is removed: init always persists, serve has nothing to save, + and runtime edits go through the admin API which persists directly. +- `PASKIA_VITE_URL` site_url fallback applies to the localhost realm + only (devserver). + +Nested rp-ids are allowed (longest-suffix dispatch determinism). Adding a +child rp-id moves **no data** โ€” users are global; only new ceremonies +stamp the child rp-id. + +### 3.3 Runtime accessors + +- The realm registry is built in the FastAPI lifespan **after + `kanta.open()`**, from `db.data().config.realms` โ€” realm data no longer + travels through `PASKIA_CONFIG` at all. Per-realm + `site_url`/`site_path` are computed at registry-build time by a shared + derivation function (same priority as today: auth_host > origins[0] > + PASKIA_VITE_URL > `http://localhost:port` > `https://rp-id`), using the + effective listen endpoints for the localhost fallback. +- `PASKIA_CONFIG` shrinks to process-global serve parameters (the + effective listen endpoints) so the derivation inside the server + process can resolve the localhost-port fallback. A welcome side effect: + `db/lifecycle.py:28-37` no longer needs `PASKIA_CONFIG` at import time + to locate the database โ€” the path is fixed (ยง10). +- `update_runtime_config` โ†’ `update_realm_runtime(rp_id, realm_config)`: + ports the site_url/site_path recomputation (`runtime.py:44-75`), + persists the combined `Config`, refreshes the registry entry in place + (dispatch must see auth_host and related-origin changes immediately). + Realm creation/deletion (ยง9) add/remove registry entries the same way. +- `util/hostutil.py` helpers take a realm parameter (`is_root_mode`, + `dedicated_auth_host`, `api_url`, `auth_site_url`, `ui_base_path`, + `reset_link_url`). `reset_link_url` has two context classes: the + bootstrap callback (`db/bootstrap.py:37-43`, no request context) uses + the **default** realm's URL; the request-context call sites + (`fastapi/user.py:294`, `admin/users.py:125`) must use the **current + request realm's** URL โ€” otherwise device-addition links mint + credentials under the wrong realm's rp-id. +- Dead code removed: `util/frontend.py`, `hostutil.reload_config`. + +## 4. Credentials get an rp-id + +- `Credential` (`structs.py:289-304`) gains `rp_id: str`, stamped at + registration from the ceremony's rp-id (`Passkey.reg_verify`, + `sansio.py:194-200`, and `Credential.create`, `structs.py:337-360`, + both gain the parameter). Field placement: `Credential` is not + `kw_only`, so the required field must precede the defaulted ones + (`structs.py:303-304`). With Related Origins the stamp is always the + _realm's canonical_ rp-id regardless of which origin the ceremony ran + on โ€” the credential genuinely is a `company.com` passkey. +- **Backfill migration** (`migrate_v6`): existing credentials get the old + stored `config.rp_id` (read from the DB's own config during replay). + `Credential` has no `omit_defaults`, so the field self-normalizes; the + migration writes the _correct_ value. +- `authenticate_chat` (`wschat.py:50-57`): the raw_id scan is filtered by + `c.rp_id == ceremony rp-id` โ€” prevents wrong error semantics and a + cross-realm oracle ("no credential" vs "verification failed" would leak + which rp-id a credential belongs to). +- `exclude_credentials` (registration, `ws.py:78`) and reauth + `allow_credentials` (`wschat.py:99-103`) are filtered by the ceremony's + rp-id โ€” `User.credential_ids` becomes cross-realm once users are global. +- Cascades are uuid-keyed and unchanged; deleting a user removes their + passkeys across all realms (correct: users are global). + +## 5. Dispatch and realm context + +- New module `paskia/realms.py`: `Realm { runtime, passkey }` and a + registry keyed by rp-id, built in the lifespan from the stored combined + `Config` (ยง3.3) and refreshed on admin realm writes. No per-realm + Kanta/DB. +- Host resolution (`resolve(host)`): normalize + (`hostutil.normalize_host`, gaining trailing-dot stripping), then + exact rp-id โ†’ exact auth_host โ†’ **exact related-origin hostname** โ†’ + longest-suffix rp-id. Unknown โ†’ `None`. (Order safe because startup and + admin-write validation forbids collisions between these sets.) +- **Pure ASGI dispatch middleware**, outermost (registered after + `redirect_middleware`), handling `"http"` and `"websocket"` scopes. + Unknown Host โ†’ 421 Misdirected Request (WS: pre-accept rejection). Sets + the `current_realm` contextvar + `request.state.realm`. +- **WebSocket resolution follows the `Origin`, not the connection + `Host`**: in auth-host mode the login page is on the app host, the WS + connects to the auth host, and Origin names the host being logged into + (docs/API.md auth-host section). So: + 1. middleware resolves the origin realm from the Origin hostname โ€” + including related-origin hostnames (a ceremony on `app2.com` for + rp-id `company.com` resolves to the `company.com` realm); + 2. the connection `Host` must be a valid WS endpoint for that realm: + the realm's _effective auth host_ (ยง6), or the origin host itself + when the realm has no auth host at all โ€” else pre-accept reject; + 3. `validate_origin` runs endpoint-side against the origin realm's + `Passkey` (post-accept JSON errors preserved, `wsutil.py:23,34-35`); + 4. `current_realm` = origin realm for the WS handler's duration. + The ceremony rp-id is always the origin realm's rp-id โ€” exactly what + the browser enforces for the page's origin under both classic and + related-origin rules. +- `paskia/globals.py` deleted; `from paskia.globals import passkey` โ†’ + `current_realm().passkey`; `db.data()` stays global. + +## 6. Auth host: per-realm values with global fallback + +A realm without its own auth host falls back to the first configured auth +host (realm-list order): + +``` +effective_auth_host(realm) = realm.auth_host or first_configured_auth_host or None +``` + +**Own vs. effective auth host must be distinguished everywhere** โ€” this +was a review finding with real consequences. The split: + +- **Follow the realm's OWN auth host**: UI mode detection + (`App.vue:43-49` minimal-profile decision), the redirect middleware + (`auth_host.py:39-53`), `ui_base_path`, and `reset_link_url`. A realm + with no own auth host keeps its full UI on its own hosts โ€” otherwise + reset/registration pages on `app2.com` would redirect to + `auth.company.com`, where the ceremony's Origin resolves the _owner_ + realm and stamps the wrong `Credential.rp_id`, breaking 2.B onboarding + and 2.C local enrollment. +- **Follow the EFFECTIVE auth host**: WS endpoint selection only + (`passkey.js:8-12` builds the WS URL from settings). The fallback auth + host serves WS + restricted APIs for foreign realms. +- Settings (`ApiSettings`) exposes both fields (add `own_auth_host` + alongside the effective `auth_host`) so the frontend can make the mode + decision correctly. +- Root mode (`site_path == "/"`) applies only on a realm's _own_ auth + host, so it is never ambiguous: a realm's UI lives on its own hosts; + the fallback auth host serves the _owner_ realm's UI plus WS for the + rest. +- Admin changes to auth_host re-validate cross-realm uniqueness against + the live registry (ยง9). + +## 7. Login flows and in-memory stores + +### 7.1 Auth codes (`authcode.py:45-113`) + +- `OIDCCode` and `CookieCode` gain `rp_id`, verified at redemption + (`oid.py:184`, `api.py:407`) โ€” defense in depth; cheap. +- **Stamping source matters** (review blocker): codes are stamped with + the realm of the session they will redeem โ€” not naively with the + current realm at issuance. Remote-completion codes are minted inside + the _permit_ handler (`remote.py:336-341`, permitting realm's context) + but redeemed by the _requesting_ device on its own host, so they are + stamped with `RemoteAuthRequest.rp_id` (ยง7.2) โ€” stamping them with the + permitter's realm would break every cross-realm remote login. + Registration-flow codes (`ws.py:97`) and OIDC codes (`ws.py:233-241`) + stamp from the current realm (issue and redeem sides always match). + The host re-check at `api.py:414-416` already binds `CookieCode` + independently; the rp_id check is additive. +- Future stores (e.g. docs/AuthTickets.md's `AuthTicket`) inherit the + rp_id field. + +### 7.2 Remote authentication โ€” cross-realm permits allowed + +- `RemoteAuthRequest` (`remoteauth.py:33-58`) gains `rp_id` โ€” the + requesting device's origin realm (resolved at `remote.py:48-49,93-98`). +- **Permit side may differ from the request side** (this is mechanism + 2.C): the permitting device authenticates with _its_ realm's passkey, + and the existing `session_host=request.host` override + (`remote.py:315-321`) creates the session for the requesting host. + Changes required: + - the `session_host` override must resolve to a **configured realm** + (registry check) โ€” today it is only non-empty-checked + (`wschat.py:108-114`); arbitrary-host session binding is refused; + - the request's rp-id is shown to the permitting user ("device at + app2.com requests login"); + - the login transaction logs both the session host and the permitting + host/credential. +- No policy flag for now: cross-realm remote login is how the product + works (users are global). A future per-realm policy field can add + isolation. +- Exchange codes stay single-use, 60s, host-bound at redemption + (`api.py:407-416` re-checks `session_ctx(secret, host)`). + +### 7.3 Same-device redirect variant (optional follow-up) + +"Logged in at auth host โ†’ bounce to app host with a code": reuse +`CookieCode` with `redirect_uri` + `state`; redeem at the target host's +`/auth/api/set-session` as today. Small addition; optional. + +## 8. OIDC: per-realm providers in one DB + +- `DB.oidc: OIDC` becomes `dict[str, OIDC]` keyed by rp-id (migration + wraps the existing struct under the old rp-id). Each realm is an + independent provider: own signing key, own clients. +- `util/oidjwt.py` key cache (`:22-24`) keyed by rp-id; keys remain + stored per realm in the DB (`structs.py:599-601`). +- Issuer stays per-request-Host (`oid.py:64-68`, discovery at + `mainapp.py:89-124`) โ€” each realm host is an issuer alias sharing the + realm's key. **`Session` gains two fields** (both `omit_defaults`, + migration-free): `issuer: str | None` โ€” stamped from the WS **Origin** + (scheme included, `ws.py:207-209`) at OIDC-session creation + (`ws.py:217-226`) and re-stamped at refresh (`oid.py:251-316`; + stamping from the WS _connection_ Host would be wrong โ€” that is the + effective auth host, not the authorize/discovery host the RP + validates against); and `rp_id: str | None` โ€” the owning realm, needed + by every path that runs **without request context**: + - backchannel logout (`oidc_notify.py:24-27` issuer, `:44` client + lookup, `:91-101` signing) uses `session.rp_id` to select the + realm's key and `session.issuer` as `iss`; + - `cleanup_expired` (`lifecycle.py:149-151`) drives the above with no + request; pre-upgrade sessions (`rp_id=None`) fall back to registry + issuerโ†’realm resolution, then the default realm; + - the logfmt UUIDโ†’label lookup (`lifecycle.py:84-93`) iterates all + realms' client dicts; + - session listings (`apistructs.py:120` `client_name`) resolve the + client under the session's own realm, not the request's. +- **Log censoring must follow the new shape (security)**: the transaction + log censor (`lifecycle.py:108-109`) matches only `oidc.key` / + `.endswith(".oidc.key")`; the new path is `oidc..key` โ€” without + a segment/regex-based rule, realm signing keys would print in plaintext + in the JSONL log and in the `migrate:v7` diff. Also harden + `_lookup_uuid_in_state` (`lifecycle.py:55`) for the nested clients. +- Admin OIDC-client CRUD operates on the current realm's `OIDC` entry. +- `_validate_permission_domain` (`admin/permissions.py:18-36`) accepts a + subdomain of **any** configured rp-id, any related-origin hostname, or + any realm's client UUID. +- `domain == client UUID` permission grouping (`oid.py:341,441`) looks up + the current realm's clients (OIDC sessions are always created under the + origin realm). + +## 9. API and frontend changes + +- `GET /auth/api/settings` (`api.py:301-316`): per-request-Host realm + values (rp_id, rp_name, effective auth_host, site URLs). Schema + unchanged. +- **Realm management (master admin only)** โ€” this is how new rp-ids are + added after bootstrap, mirroring how rp-name is already edited post + setup (`admin/server_config.py:18-78` becomes per-realm): + - New endpoints, e.g. `GET/POST /auth/api/admin/realms` and + `PATCH/DELETE /auth/api/admin/realms/{rp_id}`, gated on the + `auth:admin` scope. The admin UI gains a realm list/editor. + - Create: `rp_id` + optional `rp_name` (defaults to the rp-id), + `auth_host`, `origins`; full ยง3.1 validation (cap, cross-realm + collisions); registry entry added immediately (ยง3.3), including its + `Passkey` instance and OIDC provider entry (ยง8). + - Update: same validation against the live registry; changing a + realm's rp-id itself is **not supported** (it would orphan every + credential stamped with the old rp-id) โ€” delete and recreate + instead. + - Delete: refused for the last remaining realm and while any + credential carries the realm's rp-id (re-enroll or delete those + credentials first); cascades nothing else (users/orgs are global). + - The client-side subdomain check in `AdminDialogs.vue:70-79` must + relax to accept configured related origins. + (`AdminDialogs.vue:96`'s rp-id connectivity probe keeps working: a + related origin answers with the realm's rp_id.) +- Credential listings: `Credential.rp_id` serializes automatically into + `ApiUserDetail.credentials` (both `GET /auth/api/user-info` and + `GET /auth/api/admin/users/{uuid}` return the raw struct). +- Frontend `CredentialList.vue` (shared by ProfileView and + AdminUserDetail): rp-id badge **only when + `credential.rp_id !== settings.rp_id`** โ€” single-realm installs see no + change; even multi-realm installs only mark foreign passkeys. The + frontend already knows its rp-id (`stores/auth.js`) and already + compares rp-ids elsewhere (`AdminDialogs.vue:95-96`). +- **Enrollment prompt (2.C)**: after a cross-realm remote login, the + profile view offers "Add a passkey for faster login here" (mechanism + exists; UI wiring only). +- Bootstrap/reset links use the default realm's URL + (`db/bootstrap.py:37-43`, `paskia/bootstrap.py:40-89`). +- **Bootstrap caveat to handle**: `check_admin_credentials` + (`bootstrap.py:40-89`) prints a registration link when the first admin + "has no credentials" (`bootstrap.py:73` checks _any_ credential). With + global users, an admin may have passkeys only under _another_ realm's + rp-id โ€” the check must test for an admin credential **under the default + realm's rp-id**, or the printed link is unusable. +- Cosmetic: `admin/users.py:115` picks "user registration" vs "account + recovery" token labels from _any_ credential existing; under global + users this can mislabel (e.g. "recovery" for a user who only lacks a + passkey in this realm). `token_type` is display-only (no gating: + `api.py:369`, `structs.py:469`) โ€” adjust the wording logic, no + security impact. + +## 10. Database path, adoption, and migrations + +- Fixed CWD-relative path: **`paskia.kantadb`** โ€” a single kanta JSONL + file. Kanta rotation siblings (`paskia@.kantadb`) are + unaffected. `PASKIA_DB` removed with no replacement; + `db/paths.py:8-47` drops the rp-id parameter and the root-directory + logic. CWD selects the deployment as needed. +- **User files** (avatars, `util/avatar.py:20`) move to a fixed sibling + directory **`paskia.data/users/`** (the old `users/` lived under the + per-rp-id directory; the name `paskia.data` is a proposal, see ยง16). +- **Legacy adoption** (the only supported migration โ€” no multi-database + merging exists or is needed): if `paskia.kantadb` is absent and exactly + one `*.paskiadb` candidate exists in CWD โ€” a directory containing + `main.db`, or a legacy single-file database (`db/paths.py:39-47`'s + `_migrate_legacy_db_file` case) โ€” it is adopted: `main.db` (or the + single file) becomes `paskia.kantadb`, `users/` becomes + `paskia.data/users/`, and the old directory is removed. Multiple + candidates โ†’ startup error listing them, asking the operator to remove + or rename strays (e.g. a `*.bak.paskiadb` backup); empty directories + are ignored. Adoption runs as an explicit pre-flight step in the serve + command, **before** the read-only startup open โ€” read-only opens never + trigger adoption or migration writes (verified against kanta: read-only + opens replay migrations in memory before decode and skip all writes, + and old Config shapes decode because `migrate_v7` runs pre-decode). +- Kanta migrations (`db/migrations.py`, name-scanned `migrate_vN`): + - `migrate_v6`: `Credential.rp_id` backfill from old `config.rp_id`. + - `migrate_v7`: `Config` restructure (old fields โ†’ `realms[0]`); wrap + `oidc` under the old rp-id key. +- `kanta.ctx.rp_id` is **kept** (set to the default realm) โ€” `migrate_v2` + (`migrations.py:24`) still reads it when replaying v1-era databases; + only its role as "the" rp-id ends. Alternatively harden v2 to tolerate + a missing ctx; keeping the wiring is cheaper. +- The startup box prints per-realm lines (`util/startupbox.py`). + +## 11. Lifespan and background tasks + +- One `Kanta` for `paskia.kantadb`, constructed at import time from the + fixed path (no `PASKIA_CONFIG` dependency in `db/lifecycle.py`), opened + once in the lifespan; single bootstrap hook; one background cleanup + task (`db/background.py`) โ€” unchanged in shape (DB is global). +- The kanta bootstrap hook only ever fires for a database created by + `paskia init` (which supplies the initial combined `Config`); the serve + command never bootstraps โ€” a missing database is a startup error + pointing at `paskia init` (ยง3.2). +- Registry built from the stored `Config` after open; per-realm `Passkey` + instances constructed (each realm's origins validated at startup โ€” + fail-fast preserved, now including related-origin cap checks). +- `bootstrap_if_needed` / `check_admin_credentials` still run at serve + startup (reprint a usable registration link when the admin lacks a + credential under the default realm, ยง9). +- `oidc_notify` fire-and-forget tasks need no realm context for DB access + (global DB); issuer comes from the session (ยง8). +- The dispatch middleware is the only place `current_realm` is set; admin + realm writes refresh the registry (ยง3.3, ยง9). + +## 12. Devserver (`scripts/devserver.py`) + +- Extract init-argument parsing into an importable function (e.g. + `paskia/cliconfig.py`); `paskia init` and `devserver.py` share it โ€” no + duplicated logic. +- devserver `--rp-id`/`--auth-host` become multi-value identically + (append + comma-split) and are passed to the init step; forwarding + (`devserver.py:146-156`) loops over the initialized realms. +- Caddy dev origins (`devserver.py:167-183`): iterate all rp-ids and all + effective auth hosts (`build_caddyfile` already takes a list); the dev + Caddyfile also forwards `/.well-known/webauthn`. +- `PASKIA_AUTH_HOST` (consumed by `frontend/vite.config.js:10`) becomes + comma-joined; vite config reads the first โ€” dev-only, keep simple. + +## 13. Security model + +- **Dispatch**: unknown Host โ†’ 421 before any router/DB access (breaking + change vs today: direct-IP and unconfigured-name access stop working; + trailing dots normalized). +- **Related Origins boundary**: cross-domain origins are valid only when + explicitly configured and capped; the well-known document is served + only for the canonical realm and only lists configured origins. + Document the WG's trust warning: all origins sharing an rp-id share one + security boundary โ€” do not mix trust levels within a realm. +- **Realm administration**: realm create/update/delete is gated on + `auth:admin` (ยง9) โ€” deployment-wide by design; validation runs on every + write, not just at startup. +- **Passkeys**: rp-id binding browser-enforced and now server-recorded; + ceremonies, credential scans, exclude/allow lists all scoped to the + origin realm's rp-id. No cross-realm oracle in the scan. +- **Sessions**: unchanged โ€” host-bound, exact match. Cross-realm sessions + arise only via (a) a ceremony at the origin realm (incl. related + origins), or (b) a remote permit by a device holding a valid session at + its own realm (ยง7.2), with registry-validated target host. +- **Users/orgs global**: deleting a user/org cascades across all realms โ€” + intended. `auth:admin` is deployment-wide (document prominently). + Permission `domain` host-scoping unchanged. +- **Cross-realm permit transparency**: requesting realm/host shown to the + approver; both sides logged. +- **Secret hygiene in logs**: the OIDC signing-key censoring follows the + new `oidc..key` path shape (ยง8) โ€” without it, realm keys leak + into the JSONL transaction log. +- **OIDC**: per-realm keys/issuers; logout tokens carry the stored + issuer. + +## 14. Tests + +- `tests/conftest.py`: the import-time `PASKIA_CONFIG` seed + (`conftest.py:30-40`) goes away with the fixed DB path โ€” the app-level + Kanta and the test fixtures chdir to / open a temp directory so + `paskia.kantadb` lands there. Realm config is seeded into the DB + fixture (a two-realm config: `localhost` + `test.example.com`); + `passkey_instance` becomes a registry/current-realm fixture. + `Credential.create` call sites (`conftest.py:189-195,203-210`, + `tests/test_admin.py:95,149`) gain the `rp_id` argument. +- New tests: + - CLI: `paskia init` seeds one/multiple realms; init refuses on an + existing database; serve without a database errors; legacy adoption + (single dir, single file, multiple candidates โ†’ error, empty dir + ignored); `--save` gone. + - Admin realm management: create/validate (collisions, related-origin + cap)/update/delete rules (last realm, credential-bearing realm); + registry refresh visible to dispatch without restart. + - dispatch: 421 unknown host; trailing-dot; related-origin hostname โ†’ + owning realm (exact only โ€” `www.` variants 421); WS origin-realm + resolution; WS to auth host with app-host Origin accepted; arbitrary + Host/Origin combos rejected. + - credentials: rp_id stamping (incl. ceremony on a related origin โ†’ + canonical rp-id); backfill migration; scan/exclude/allow filtering; + no cross-realm oracle. + - **Related Origins server-side (pytest only)**: origin-validation + rules (subtree-OR-listed), `/.well-known/webauthn` contents and + absence-when-unconfigured. **Not e2e**: a genuine related origin + needs a non-subdomain host over HTTPS, and the browser fetches the + well-known document from the browser process itself โ€” not + interceptable in the current plain-HTTP harness + (`playwright.config.js:27`). E2E for ROR requires deliberate TLS/DNS + infra; skip unless that is built. + - cross-realm remote login end-to-end (request at realm B, permit at + realm A, session valid only on B's host); exchange codes minted in + the permit path redeem on the requester's realm (ยง7.1); arbitrary + `session_host` refused. + - bootstrap caveat: admin with only foreign-realm credentials still + gets a usable registration link for the default realm. + - OIDC: per-realm keys/issuers; issuer stamped from WS Origin (not the + connection Host); refresh re-stamps; backchannel logout selects the + session realm's key with no request context; log censoring covers + `oidc..key`. +- E2E: `global-setup.ts` drops `PASKIA_DB`, spawns `paskia init --rp-id + localhost,test.localhost` with `cwd` in the tmp dir, then serves; add a + `http://test.localhost:4404` project exercising dispatch and a + cross-realm remote login (remote auth currently has no e2e coverage; + this feature needs it). + +## 15. Docs and compatibility + +- README: multi-realm model, `paskia init` bootstrap, combined DB at + `paskia.kantadb`, `PASKIA_DB` removal, Related Origins setup. +- docs/API.md: auth-host section rewritten for own-vs-effective fallback + semantics and cross-realm behavior; `/.well-known/webauthn` documented; + realm-management admin endpoints documented. +- **Related Origins deployment guidance** (the critical operational + bit): the browser fetches `https:///.well-known/webauthn` from + the canonical apex directly. If paskia hosts the apex, our endpoint + serves it; if the apex is hosted elsewhere (typical for marketing + domains), the JSON must be published there statically. Existing + examples serve `/.well-known/*` statically (`docs/proxy/caddy.md`, + `caddy/Caddyfile:10-14`) โ€” they must not shadow paskia's endpoint when + paskia does host it. +- docs/proxy + `caddy/auth/setup`: forward + `/.well-known/openid-configuration` **and** `/.well-known/webauthn`; + the vite dev proxy allowlist (`frontend/vite.config.js:16-24`) gains + both paths; Host preservation requirement unchanged. +- `oidc.md` (root): updated for per-realm providers and `Session.issuer`. +- Breaking changes: DB moved to `paskia.kantadb` (auto-adopted from a + lone legacy `*.paskiadb`; `PASKIA_DB` removed), serve command drops all + realm options and `--save` (use `paskia init` / the admin interface), + `PASKIA_CONFIG` format reduced to serve parameters, + `Config`/`DB.oidc`/`Credential` schema migrations, `paskia/globals.py` + removed, unknown Host โ†’ 421, `paskia.util.frontend` removed. + +## 16. Open questions + +1. Same-device redirect flow (ยง7.3): include in this release or defer? +2. User-files directory name: `paskia.data/` (proposed) vs something + else; it holds only avatars today. +3. Bare `paskia` with no database: proposed behavior is a startup error + pointing at `paskia init`. Alternative: keep today's zero-config dev + experience by auto-initializing a `localhost` realm. Strictness avoids + bootstrap/runtime mixups; auto-init is friendlier for first contact. + +(Settled during review, for the record: fallback-auth-host UI semantics โ€” +a realm's UI lives on its own hosts, the fallback auth host serves WS and +restricted APIs for foreign realms plus the owner realm's UI; settings +exposes own vs. effective auth host, ยง6. OIDC logout signing without +request context โ€” `Session.rp_id` + `Session.issuer` fields, ยง8. Related +Origins e2e โ€” pytest only, ยง14. Realm configuration after bootstrap โ€” +admin interface only, serve takes no realm options, ยง3.2. Combined DB +name and location โ€” `paskia.kantadb` in CWD, ยง10.) -- 2.55.0 From 4591a023dd544df43064218ea6bb74208c3dd4f9 Mon Sep 17 00:00:00 2001 From: Leo Vasanko Date: Sun, 6 Sep 2026 03:50:06 +0000 Subject: [PATCH 04/48] Clean-slate storage: realms Config, Credential.rp_id, Session rp_id/issuer, per-realm OIDC - Config is now a realm list (first = default); DB.oidc keyed by rp-id - Database at fixed paskia.kantadb; user files under paskia.data/users/ - Legacy .paskiadb reader/converter in db/legacy.py (to be deleted eventually) - paskia init / paskia serve CLI split; serve adopts a lone legacy database - Realm registry (paskia/realms.py) with cross-realm validation - Per-realm OIDC keys in oidjwt; backchannel logout uses Session.rp_id/issuer - Schema migrations discarded; on-disk legacy format assumed current --- paskia/__main__.py | 287 +++++++++++++++++++++-------------- paskia/bootstrap.py | 51 +++---- paskia/db/__init__.py | 10 ++ paskia/db/bootstrap.py | 15 +- paskia/db/legacy.py | 243 ++++++++++++++++++++++++++++++ paskia/db/lifecycle.py | 57 ++++--- paskia/db/migrations.py | 48 ------ paskia/db/operations.py | 107 +++++++++++-- paskia/db/paths.py | 52 +++---- paskia/db/structs.py | 77 ++++++++-- paskia/oidc_notify.py | 53 +++++-- paskia/realms.py | 306 ++++++++++++++++++++++++++++++++++++++ paskia/sansio.py | 65 ++++---- paskia/util/hostutil.py | 82 ++++------ paskia/util/oidjwt.py | 86 ++++++----- paskia/util/runtime.py | 79 +++------- paskia/util/startupbox.py | 50 ++++--- 17 files changed, 1149 insertions(+), 519 deletions(-) create mode 100644 paskia/db/legacy.py delete mode 100644 paskia/db/migrations.py create mode 100644 paskia/realms.py diff --git a/paskia/__main__.py b/paskia/__main__.py index 4c4a15f..eadabd0 100644 --- a/paskia/__main__.py +++ b/paskia/__main__.py @@ -11,8 +11,13 @@ from fastapi_vue.hostutil import parse_endpoints from kanta import Kanta from paskia._version import __version__ +from paskia.db import legacy +from paskia.db.bootstrap import bootstrap, log_reset_link from paskia.db.paths import db_file_path -from paskia.db.structs import DB, Config +from paskia.db.structs import DB, Config, RealmConfig +from paskia.realms import build as build_registry +from paskia.realms import configure as configure_realms +from paskia.realms import validate_config from paskia.util import startupbox from paskia.util.constants import DEFAULT_PORT, DEVMODE from paskia.util.hostutil import ( @@ -20,52 +25,44 @@ from paskia.util.hostutil import ( normalize_origin, validate_auth_host, ) -from paskia.util.runtime import RuntimeConfig +from paskia.util.runtime import ServeConfig EPILOG = """\ -Example: - paskia --rp-id example.com --rp-name "Example Corporation" --auth-host auth.example.com +Examples: + paskia init --rp-id example.com --rp-name "Example Corporation" --auth-host auth.example.com + paskia """ -def add_common_options(p: argparse.ArgumentParser) -> None: +def _split_multi(values: list[str] | None) -> list[str]: + """Split repeatable/comma-separated CLI values into a flat list.""" + result = [] + for value in values or []: + result.extend(part.strip() for part in value.split(",") if part.strip()) + return result + + +def _add_listen_option(p: argparse.ArgumentParser, help_extra: str = "") -> None: p.add_argument( - "--rp-id", default="localhost", help="Relying Party ID (default: localhost)" - ) - p.add_argument("--rp-name", help="Relying Party name (default: same as rp-id)") - p.add_argument( - "--origin", + "-l", + "--listen", action="append", - dest="origins", - metavar="URL", - help="Allowed origin URL(s). May be specified multiple times. If any are specified, only those origins are permitted for WebSocket authentication.", - ) - p.add_argument( - "--auth-host", - help=("Dedicated authentication site (optionally with scheme/port)"), - ) - p.add_argument( - "--save", - action="store_true", - help="Save the CLI options to database for future runs.", + metavar="LISTEN", + help=( + "Endpoint to listen on (default: localhost:4401). " + "Forms: host:port port :port [ipv6]:port unix:path /path.sock" + ) + + help_extra, ) -def _load_stored_config(db_path: Path, *, rp_id: str) -> Config: +def _load_stored_config(db_path: Path) -> Config: """Load the stored Config from disk using Kanta in read-only mode. This must not depend on PASKIA_CONFIG or the global lifecycle Kanta. - If the database file does not exist, a default config is returned. + Read-only opens never write or migrate the file. """ - if not db_path.exists(): - return Config(rp_id=rp_id) - - kanta = Kanta( - str(db_path), - DB(config=Config(rp_id=rp_id)), - migrations="paskia.db.migrations", - ) - kanta.ctx.rp_id = rp_id + kanta = Kanta(str(db_path), DB()) async def _read() -> Config: await kanta.open(readonly=True) @@ -81,6 +78,117 @@ def _load_stored_config(db_path: Path, *, rp_id: str) -> Config: raise SystemExit(f"{e}") from e +def cmd_init(args: argparse.Namespace) -> None: + """Bootstrap a new paskia.kantadb database with the initial realm(s).""" + db_path = db_file_path() + if db_path.exists(): + raise SystemExit( + f"Database {db_path} already exists โ€” realm configuration is " + "managed via the admin interface, not 'paskia init'." + ) + if found := legacy.find_legacy_databases(): + names = ", ".join(str(p) for p in found) + raise SystemExit( + f"Legacy database(s) found ({names}) โ€” run 'paskia' to adopt " + "and convert, not 'paskia init'." + ) + + rp_ids = _split_multi(args.rp_id) or ["localhost"] + + realms = [] + for i, rp_id in enumerate(rp_ids): + realm = RealmConfig(rp_id=rp_id) + if i == 0: + # Bootstrap-time naming and hosts apply to the default realm; + # everything is editable via the admin interface afterwards. + realm.rp_name = args.rp_name or None + origins = ( + [normalize_origin(o) for o in _split_multi(args.origins)] or None + ) + auth_host = args.auth_host or None + if auth_host: + validate_auth_host(auth_host, rp_id) + realm.auth_host, realm.origins = normalize_auth_host_and_origins( + auth_host, origins + ) + realms.append(realm) + + config = Config(realms=realms, listen=_split_multi(args.listen) or None) + try: + validate_config(config) + except ValueError as e: + raise SystemExit(str(e)) from e + + # Create the database; the kanta bootstrap callback seeds it (admin + # user, org, permissions, reset token, per-realm OIDC keys). + new_db = DB() + kanta = Kanta(str(db_path), new_db) + result = {} + + @kanta.bootstrap + def _bootstrap(data: DB) -> None: + result["passphrase"] = bootstrap(data, config=config) + + async def _create() -> None: + async with kanta: + pass + + try: + asyncio.run(_create()) + except Exception as e: + logging.exception("Failed to create database") + db_path.unlink(missing_ok=True) + raise SystemExit(f"{e}") from e + + configure_realms(listen=config.listen) + registry = build_registry(config) + startupbox.print_startup_config(registry, listen=config.listen) + log_reset_link( + registry.default.reset_link_url(result["passphrase"]), + "โœ… Bootstrap completed!", + ) + + +def cmd_serve(args: argparse.Namespace) -> None: + """Open the combined database and serve all configured realms.""" + db_path = db_file_path() + if not db_path.exists(): + adopted = legacy.adopt_legacy_if_present() + if adopted: + print(f"โœ… Converted legacy database to {db_path} (realm: {adopted})") + if not db_path.exists(): + raise SystemExit( + f"Database {db_path} not found โ€” run 'paskia init' first." + ) + + config = _load_stored_config(db_path) + try: + validate_config(config) + except ValueError as e: + raise SystemExit(f"Invalid stored configuration: {e}") from e + + listen = _split_multi(args.listen) or config.listen + configure_realms(listen=listen) + registry = build_registry(config) + + # Pass process-global serve parameters to the server process(es) + os.environ["PASKIA_CONFIG"] = msgspec.json.encode(ServeConfig(listen=listen)).decode() + + startupbox.print_startup_config(registry, listen=listen) + + # Run the server (spawns processes in dev mode) + # tracerite, access logging and log config are handled by fastapi_vue.server; + # we print our own startup config box, so disable the built-in one. + server.run( + "paskia.fastapi.mainapp:app", + listen=listen, + default_port=DEFAULT_PORT, + server_header=False, + startup_box=None, + reload=Path(__file__).parent if DEVMODE else False, + ) + + def main(): # Configure logging to remove the "ERROR:root:" prefix logging.basicConfig(level=logging.INFO, format="%(message)s", force=True) @@ -91,91 +199,46 @@ def main(): formatter_class=argparse.RawDescriptionHelpFormatter, epilog=EPILOG, ) + _add_listen_option(parser) - parser.add_argument( - "-l", - "--listen", + init_parser = argparse.ArgumentParser( + prog="paskia init", + description="Bootstrap a new paskia.kantadb database in the current directory", + formatter_class=argparse.RawDescriptionHelpFormatter, + epilog=EPILOG, + ) + init_parser.add_argument( + "--rp-id", action="append", - metavar="LISTEN", - help=( - "Endpoint to listen on (default: localhost:4401). " - "Forms: host:port port :port [ipv6]:port unix:path /path.sock" - ), + help="Relying Party ID of the initial realm(s) (default: localhost). " + "Repeatable and comma-separated; the first is the default realm. " + "Further realms are added via the admin interface.", ) - add_common_options(parser) - - args = parser.parse_args() - - # Load stored config using a local read-only Kanta instance. - # This happens before PASKIA_CONFIG is set, so we must not import - # modules that initialize the global database lifecycle. - db_path = db_file_path(rp_id=args.rp_id, create_root=True) - try: - config = _load_stored_config(db_path, rp_id=args.rp_id) - except SystemExit as e: - print(f"๐Ÿ›‘ Paskia {__version__} could not load") - sys.exit(str(e)) - - # Override stored config with CLI args, or clear with empty string - if args.rp_name is not None: - config.rp_name = args.rp_name or None - if args.auth_host is not None: - config.auth_host = args.auth_host or None - if args.origins is not None: - config.origins = None if args.origins == [""] else args.origins - if args.listen is not None: - config.listen = None if args.listen == [""] else args.listen - - # Process and normalize auth_host and origins - try: - validate_auth_host(config.auth_host, config.rp_id) if config.auth_host else None - except ValueError as e: - raise SystemExit(str(e)) - if config.origins: - config.origins = [normalize_origin(o) for o in config.origins] - config.auth_host, config.origins = normalize_auth_host_and_origins( - config.auth_host, config.origins + init_parser.add_argument( + "--rp-name", + help="Relying Party name of the default realm (default: same as rp-id). " + "Used by the initial admin registration; editable later via admin UI.", ) + init_parser.add_argument( + "--origin", + action="append", + dest="origins", + metavar="URL", + help="Allowed origin URL(s) for the default realm. May be specified " + "multiple times; comma-separated values accepted.", + ) + init_parser.add_argument( + "--auth-host", + help="Dedicated authentication site for the default realm " + "(optionally with scheme/port)", + ) + _add_listen_option(init_parser, help_extra=" (stored in the database)") - # Parse first endpoint for site_url fallback - ep = next(iter(parse_endpoints(config.listen, DEFAULT_PORT)), {}) - port = ep.get("port") - - # Compute site_url and site_path - # Priority: auth_host > origins[0] > PASKIA_VITE_URL > http://localhost:port > https://rp_id - site_path = "/auth/" - if config.auth_host: - site_url, site_path = config.auth_host, "/" - elif config.origins: - site_url = config.origins[0] - elif vite_url := os.environ.get("PASKIA_VITE_URL"): - site_url = vite_url.rstrip("/") # Devserver - elif config.rp_id == "localhost" and port: - site_url = f"http://localhost:{port}" # Backend directly if we can + argv = sys.argv[1:] + if argv and argv[0] == "init": + cmd_init(init_parser.parse_args(argv[1:])) else: - site_url = f"https://{config.rp_id}" # Assume external reverse proxy - - # Build runtime configuration for the server - runtime = RuntimeConfig( - config=config, - site_url=site_url, - site_path=site_path, - save=args.save, - ) - startupbox.print_startup_config(runtime) - os.environ["PASKIA_CONFIG"] = msgspec.json.encode(runtime).decode() - - # Run the server (spawns processes in dev mode) - # tracerite, access logging and log config are handled by fastapi_vue.server; - # we print our own startup config box, so disable the built-in one. - server.run( - "paskia.fastapi.mainapp:app", - listen=config.listen, - default_port=DEFAULT_PORT, - server_header=False, - startup_box=None, - reload=Path(__file__).parent if DEVMODE else False, - ) + cmd_serve(parser.parse_args(argv)) if __name__ == "__main__": diff --git a/paskia/bootstrap.py b/paskia/bootstrap.py index 9c05234..0d93afb 100644 --- a/paskia/bootstrap.py +++ b/paskia/bootstrap.py @@ -1,20 +1,17 @@ """ Bootstrap module for passkey authentication system. -This module handles initial system setup when a new database is created, -including creating default admin user, organization, permissions, and -generating a reset link for initial admin setup. - -The actual database seeding is performed by the module-level kanta bootstrap -callback defined in :mod:`paskia.db.bootstrap` and registered during -:func:`paskia.db.lifecycle.init`. +The initial database seeding (admin user, organization, permissions, +registration reset token) is performed by ``paskia init`` via +:func:`paskia.db.bootstrap.bootstrap`. This module provides the serve-time +check that re-prints a registration link when the admin user still has no +passkey under the default realm. """ import logging -from paskia import authsession, db +from paskia import authsession, db, realms from paskia.db.bootstrap import log_reset_link -from paskia.db.structs import Config logger = logging.getLogger(__name__) @@ -32,15 +29,14 @@ def _configure_logger() -> None: _configure_logger() -def _log_reset_link(passphrase: str, message: str | None = None) -> str: - """Log a reset link message and return the URL.""" - return log_reset_link(passphrase, message) - - async def check_admin_credentials() -> bool: """ Check if the admin user needs credentials and create a reset link if needed. + With global users, the admin may hold passkeys under other realms only โ€” + the check tests for a credential under the **default realm's** rp-id, so + the printed link (which points at the default realm) is usable. + Returns: bool: True if a reset link was created, False if admin already has credentials """ @@ -67,12 +63,13 @@ async def check_admin_credentials() -> bool: if not admin_users: return False - # Check first admin user for credentials + # Check first admin user for credentials under the default realm admin_user = admin_users[0] + default = realms.registry().default - if not admin_user.credential_ids: - # Admin exists but has no credentials, create reset link - logger.info("โš ๏ธ Admin user has no credentials!") + if not admin_user.credential_ids_for(default.rp_id): + # Admin exists but has no credential on the default realm + logger.info("โš ๏ธ Admin user has no credentials on %s!", default.rp_id) expiry = authsession.reset_expires() token = db.create_reset_token( @@ -80,7 +77,7 @@ async def check_admin_credentials() -> bool: expiry=expiry, token_type="admin registration", ) - _log_reset_link(token) + log_reset_link(default.reset_link_url(token)) return True return False @@ -89,20 +86,12 @@ async def check_admin_credentials() -> bool: return False -async def bootstrap_if_needed(config: Config | None = None) -> bool: - """ - Check if admin needs credentials and create a reset link if needed. - - Database bootstrapping itself is now handled automatically during - ``db.init()`` via the registered kanta bootstrap callback. This function - remains as a post-init hook for credential checks. - - Args: - config: Kept for backwards compatibility; config is now applied during - ``db.init()``. +async def bootstrap_if_needed() -> bool: + """Run the serve-time admin credential check. Returns: - bool: Always returns False (bootstrapping is performed during init). + bool: Always returns False (bootstrapping is performed by ``paskia init``). """ await check_admin_credentials() return False + diff --git a/paskia/db/__init__.py b/paskia/db/__init__.py index cdafc6a..7ad8f82 100644 --- a/paskia/db/__init__.py +++ b/paskia/db/__init__.py @@ -28,6 +28,7 @@ from paskia.db.operations import ( create_oid_client, create_org, create_permission, + create_realm, create_reset_token, create_role, create_user, @@ -35,6 +36,7 @@ from paskia.db.operations import ( delete_oid_client, delete_org, delete_permission, + delete_realm, delete_reset_token, delete_role, delete_session, @@ -52,6 +54,7 @@ from paskia.db.operations import ( update_oid_client, update_org_name, update_permission, + update_realm, update_role_name, update_session, update_user_display_name, @@ -60,11 +63,13 @@ from paskia.db.operations import ( ) from paskia.db.structs import ( DB, + OIDC, Client, Config, Credential, Org, Permission, + RealmConfig, ResetToken, Role, Session, @@ -84,8 +89,10 @@ __all__ = [ "Credential", "DB", "Client", + "OIDC", "Org", "Permission", + "RealmConfig", "ResetToken", "Role", "Session", @@ -102,12 +109,14 @@ __all__ = [ "create_credential_session", "create_org", "create_permission", + "create_realm", "create_reset_token", "create_role", "create_user", "delete_credential", "delete_org", "delete_permission", + "delete_realm", "delete_reset_token", "delete_role", "delete_session", @@ -122,6 +131,7 @@ __all__ = [ "update_credential_sign_count", "update_org_name", "update_permission", + "update_realm", "update_role_name", "update_session", "update_user_display_name", diff --git a/paskia/db/bootstrap.py b/paskia/db/bootstrap.py index 44fbae3..14f9057 100644 --- a/paskia/db/bootstrap.py +++ b/paskia/db/bootstrap.py @@ -9,9 +9,8 @@ from datetime import UTC, datetime import uuid7 from paskia.authsession import reset_expires -from paskia.db.structs import DB, Config, Org, Permission, ResetToken, Role, User +from paskia.db.structs import DB, Config, OIDC, Org, Permission, ResetToken, Role, User from paskia.util.crypto import secret_key -from paskia.util.hostutil import reset_link_url _reset_link_logger = logging.getLogger("paskia.reset_link") @@ -34,13 +33,12 @@ ADMIN_RESET_MESSAGE = """ """ -def log_reset_link(passphrase: str, message: str | None = None) -> str: +def log_reset_link(url: str, message: str | None = None) -> str: """Log a reset link message and return the URL.""" - reset_link = reset_link_url(passphrase) if message: _reset_link_logger.info(message) - _reset_link_logger.info(ADMIN_RESET_MESSAGE, reset_link) - return reset_link + _reset_link_logger.info(ADMIN_RESET_MESSAGE, url) + return url def bootstrap( @@ -147,8 +145,9 @@ def bootstrap( if config is not None: data.config = config - # Generate OIDC signing key - data.oidc.key = secret_key() + # Generate an OIDC signing key for each realm + rp_ids = [r.rp_id for r in data.config.realms] + data.oidc = {rp_id: OIDC(key=secret_key()) for rp_id in rp_ids} # Store all bootstrapped objects in the live data object data.permissions[perm_admin_uuid] = perm_admin diff --git a/paskia/db/legacy.py b/paskia/db/legacy.py new file mode 100644 index 0000000..1050c9f --- /dev/null +++ b/paskia/db/legacy.py @@ -0,0 +1,243 @@ +"""Legacy database format reader and converter. + +Retains the msgspec structs used by the old ``.paskiadb/main.db`` +format so existing databases can be opened and converted to the combined +``paskia.kantadb`` format. Only the structs whose shape differs from the +current schema are redefined here; unchanged structs are imported from +``paskia.db.structs``. + +Assumes the on-disk records are in the latest legacy format (schema +migrations were discarded together with the old format). This module will +be deleted once legacy adoption is no longer supported. +""" + +from __future__ import annotations + +import asyncio +import shutil +from datetime import datetime +from pathlib import Path +from uuid import UUID + +import msgspec +from kanta import Kanta + +from paskia.db.paths import db_file_path, users_root_path +from paskia.db.structs import ( + OIDC, + DB, + Config, + Credential, + Org, + Permission, + RealmConfig, + ResetToken, + Role, + Session, + User, +) + + +class LegacyConfig(msgspec.Struct, omit_defaults=True): + """Pre-realms stored configuration (single rp-id per database).""" + + rp_id: str + rp_name: str | None = None + auth_host: str | None = None + origins: list[str] | None = None + listen: list[str] | None = None + + +class LegacyCredential(msgspec.Struct, dict=True): + """Credential without the rp_id stamp.""" + + credential_id: bytes + user_uuid: UUID = msgspec.field(name="user") + aaguid: UUID + public_key: bytes + sign_count: int + created_at: datetime + last_used: datetime | None = None + last_verified: datetime | None = None + + +class LegacySession(msgspec.Struct, dict=True, omit_defaults=True): + """Session without the rp_id/issuer stamps.""" + + user_uuid: UUID = msgspec.field(name="user") + credential_uuid: UUID = msgspec.field(name="credential") + host: str + ip: str + user_agent: str + validated: datetime + client_uuid: UUID | None = msgspec.field(name="client", default=None) + + +class LegacyDB(msgspec.Struct, dict=True, omit_defaults=False): + """Root structure of a legacy single-rp-id database.""" + + config: LegacyConfig = msgspec.field( + default_factory=lambda: LegacyConfig(rp_id="localhost") + ) + permissions: dict[UUID, Permission] = {} + orgs: dict[UUID, Org] = {} + roles: dict[UUID, Role] = {} + users: dict[UUID, User] = {} + credentials: dict[UUID, LegacyCredential] = {} + sessions: dict[str, LegacySession] = {} + reset_tokens: dict[str, ResetToken] = {} + oidc: OIDC = msgspec.field(default_factory=OIDC) + + +def _read_legacy(path: Path) -> LegacyDB: + """Open a legacy database read-only and return its contents.""" + kanta = Kanta(str(path), LegacyDB()) + + async def _read() -> LegacyDB: + await kanta.open(readonly=True) + return kanta.data + + return asyncio.run(_read()) + + +def convert_legacy_database(src: Path, dst: Path) -> Config: + """Convert a legacy main.db file into the combined kantadb format. + + Reads the legacy database at ``src`` and writes a fresh database at + ``dst``. All credentials and sessions are stamped with the legacy + database's rp-id; the OIDC provider is moved under that rp-id key. + Returns the converted (new-format) configuration. + """ + old = _read_legacy(src) + rp_id = old.config.rp_id + + new_config = Config( + realms=[ + RealmConfig( + rp_id=rp_id, + rp_name=old.config.rp_name, + auth_host=old.config.auth_host, + origins=old.config.origins, + ) + ], + listen=old.config.listen, + ) + + credentials = { + uuid: Credential( + credential_id=c.credential_id, + user_uuid=c.user_uuid, + aaguid=c.aaguid, + public_key=c.public_key, + sign_count=c.sign_count, + created_at=c.created_at, + rp_id=rp_id, + last_used=c.last_used, + last_verified=c.last_verified, + ) + for uuid, c in old.credentials.items() + } + sessions = { + key: Session( + user_uuid=s.user_uuid, + credential_uuid=s.credential_uuid, + host=s.host, + ip=s.ip, + user_agent=s.user_agent, + validated=s.validated, + client_uuid=s.client_uuid, + rp_id=rp_id, + ) + for key, s in old.sessions.items() + } + + converted = DB( + config=new_config, + permissions=old.permissions, + orgs=old.orgs, + roles=old.roles, + users=old.users, + credentials=credentials, + sessions=sessions, + reset_tokens=old.reset_tokens, + oidc={rp_id: old.oidc}, + ) + + new_db = DB() + kanta = Kanta(str(dst), new_db) + + @kanta.bootstrap + def _seed(data: DB) -> None: + data.config = converted.config + data.permissions = converted.permissions + data.orgs = converted.orgs + data.roles = converted.roles + data.users = converted.users + data.credentials = converted.credentials + data.sessions = converted.sessions + data.reset_tokens = converted.reset_tokens + data.oidc = converted.oidc + + async def _write() -> None: + async with kanta: + pass + + asyncio.run(_write()) + return new_config + + +def find_legacy_databases(cwd: Path | None = None) -> list[Path]: + """Find legacy ``*.paskiadb`` databases in a directory. + + A candidate is either a directory containing ``main.db`` or a legacy + single-file database. Empty directories and non-matching files are + ignored. + """ + cwd = cwd or Path.cwd() + candidates = [] + for entry in sorted(cwd.glob("*.paskiadb")): + if entry.is_dir(): + if (entry / "main.db").is_file(): + candidates.append(entry) + elif entry.is_file(): + candidates.append(entry) + return candidates + + +def adopt_legacy_if_present() -> str | None: + """Convert a lone legacy database to ``paskia.kantadb`` if present. + + Returns the adopted realm's rp-id, or None when ``paskia.kantadb`` + already exists or no legacy database is present. The converted legacy + directory/file is renamed aside to ``.converted-bak`` rather than + deleted. + + Raises SystemExit when multiple legacy databases are found โ€” automatic + merging is not supported. + """ + target = db_file_path() + if target.exists(): + return None + candidates = find_legacy_databases() + if not candidates: + return None + if len(candidates) > 1: + names = ", ".join(str(c) for c in candidates) + raise SystemExit( + f"Multiple legacy databases found ({names}). Automatic merging is " + "not supported โ€” remove or rename all but the one to adopt." + ) + + src = candidates[0] + legacy_file = src / "main.db" if src.is_dir() else src + config = convert_legacy_database(legacy_file, target) + + # Move persisted user files (avatars) to the new data root + legacy_users = src / "users" if src.is_dir() else None + if legacy_users is not None and legacy_users.is_dir(): + target_users = users_root_path(create_root=True) + for child in legacy_users.iterdir(): + shutil.move(str(child), str(target_users / child.name)) + + shutil.move(str(src), str(src.with_name(src.name + ".converted-bak"))) + return config.default_realm.rp_id diff --git a/paskia/db/lifecycle.py b/paskia/db/lifecycle.py index 06a4b4b..b8bb58a 100644 --- a/paskia/db/lifecycle.py +++ b/paskia/db/lifecycle.py @@ -5,6 +5,7 @@ Database lifecycle: initialization and maintenance. import asyncio import logging import os +import re import signal from datetime import UTC, datetime from pathlib import Path @@ -17,24 +18,14 @@ from kanta.exceptions import DatabaseError import paskia.db.operations as _ops from paskia import oidc_notify from paskia.authsession import EXPIRES -from paskia.db.bootstrap import bootstrap, log_reset_link from paskia.db.paths import db_file_path from paskia.db.structs import DB -from paskia.util.runtime import config as runtime_config logger = logging.getLogger(__name__) - -runtime = runtime_config() -if runtime is None: - raise RuntimeError("PASKIA_CONFIG must be defined before importing db.lifecycle") - -kanta = Kanta( - str(db_file_path(rp_id=runtime.config.rp_id, create_root=False)), - _ops._db, - migrations="paskia.db.migrations", -) -kanta.ctx.rp_id = runtime.config.rp_id +# The combined database lives at a fixed CWD-relative path; no runtime +# configuration is needed to locate it. +kanta = Kanta(str(db_file_path()), _ops._db) _ops._db._store = kanta @@ -51,12 +42,16 @@ def _lookup_uuid_in_state(state: dict | None, uuid_str: str) -> str | None: if isinstance(display_name, str) and display_name: return display_name - # OIDC clients use "name" instead of "display_name". - client = state.get("oidc", {}).get("clients", {}).get(uuid_str) - if isinstance(client, dict): - name = client.get("name") - if isinstance(name, str) and name: - return name + # OIDC clients use "name" instead of "display_name"; providers are + # nested per realm rp-id. + for provider in state.get("oidc", {}).values(): + if not isinstance(provider, dict): + continue + client = provider.get("clients", {}).get(uuid_str) + if isinstance(client, dict): + name = client.get("name") + if isinstance(name, str) and name: + return name return None @@ -89,11 +84,16 @@ def _resolve_uuid_label( return _ops._db.roles[uid].display_name if uid in _ops._db.permissions: return _ops._db.permissions[uid].display_name - if uid in _ops._db.oidc.clients: - return _ops._db.oidc.clients[uid].name + for provider in _ops._db.oidc.values(): + if uid in provider.clients: + return provider.clients[uid].name return None +# OIDC signing keys are stored at oidc..key (rp-ids contain dots). +_OIDC_KEY_PATH = re.compile(r"^oidc\..+\.key$") + + @kanta.logfmt def format_log_uuid( value: Any, @@ -104,8 +104,8 @@ def format_log_uuid( """Format UUID values/keys/actor labels and censor secrets in transaction logs.""" # Censor sensitive OIDC key material regardless of value type, but only # when formatting the value: path components are passed with the component - # itself as value and must stay visible ("oidc.key = "). - if (path == "oidc.key" or path.endswith(".oidc.key")) and value != "key": + # itself as value and must stay visible ("oidc..key = "). + if _OIDC_KEY_PATH.fullmatch(path) and value != "key": return "" if not isinstance(value, str): @@ -122,17 +122,12 @@ def terminate(error: DatabaseError) -> None: os.kill(os.getpid(), signal.SIGTERM) -@kanta.bootstrap -def bootstrap_db(data: DB) -> None: - reset_passphrase = bootstrap(data, config=runtime.config) - log_reset_link(reset_passphrase, "โœ… Bootstrap completed!") - - async def init(): """Load database from JSONL file using kanta. - If the database file is empty, the configured bootstrap callback seeds it - with default permissions, organization, role, admin user and a reset token. + The database must already exist and be initialized (see ``paskia + init``); the serve command's startup checks guarantee this before the + lifespan runs. """ rootpath = Path(kanta.filename).parent try: diff --git a/paskia/db/migrations.py b/paskia/db/migrations.py deleted file mode 100644 index ff2ce33..0000000 --- a/paskia/db/migrations.py +++ /dev/null @@ -1,48 +0,0 @@ -""" -Database schema migrations. - -Migrations are applied during database load based on the version field. -Each migration should be idempotent and only run when needed. -""" - -import base64 - -from kanta import Kanta - -from paskia.util.crypto import secret_key - - -def migrate_v1(d: dict) -> None: - """Remove Org.created_at fields.""" - for org_data in d["orgs"].values(): - org_data.pop("created_at", None) - - -def migrate_v2(d: dict, kanta: Kanta) -> None: - """Add config field if missing.""" - if "config" not in d: - d["config"] = {"rp_id": kanta.ctx.rp_id} - - -def migrate_v3(d: dict) -> None: - """Ensure all users have visits field.""" - for user_data in d["users"].values(): - user_data.setdefault("visits", 0) - - -def migrate_v4(d: dict) -> None: - """OpenID Connect support and hardened session keys.""" - # Session keys changed to hashes, drop old sessions - d["sessions"] = {} - # Create OIDC structure with a generated new key - d["oidc"] = { - "clients": {}, - "key": base64.standard_b64encode(secret_key()).decode(), - } - - -def migrate_v5(d: dict) -> None: - """Convert config.listen from str to list[str] if needed.""" - listen = d["config"].get("listen") - if listen and isinstance(listen, str): - d["config"]["listen"] = [listen] diff --git a/paskia/db/operations.py b/paskia/db/operations.py index 6853ed3..a0b363e 100644 --- a/paskia/db/operations.py +++ b/paskia/db/operations.py @@ -17,18 +17,20 @@ from paskia import oidc_notify from paskia.config import SESSION_LIFETIME from paskia.db.structs import ( DB, + OIDC, Client, Config, Credential, Org, Permission, + RealmConfig, ResetToken, Role, Session, SessionContext, User, ) -from paskia.util.crypto import hash_secret +from paskia.util.crypto import hash_secret, secret_key from paskia.util.nameutil import slugify_name _logger = logging.getLogger(__name__) @@ -37,7 +39,7 @@ _logger = logging.getLogger(__name__) _UNSET = object() # Global database instance (empty until init() loads data) -_db = DB(config=Config(rp_id="uninitialized.invalid")) +_db = DB() def _store(): @@ -703,20 +705,89 @@ def create_credential_session( return token +# ------------------------------------------------------------------------- +# Realm operations +# ------------------------------------------------------------------------- + + +def _oidc_provider(rp_id: str) -> OIDC: + """Return the OIDC provider entry for a realm, raising if missing.""" + provider = _db.oidc.get(rp_id) + if provider is None: + raise ValueError(f"Realm {rp_id} not found") + return provider + + +def create_realm(realm: RealmConfig, *, ctx: SessionContext | None = None) -> None: + """Add a new realm (rp-id) to the stored configuration. + + Seeds an OIDC provider entry (with a fresh signing key) for the realm. + The caller must validate the resulting combined configuration. + """ + if _db.config.find_realm(realm.rp_id) is not None: + raise ValueError(f"Realm {realm.rp_id} already exists") + with _transaction("admin:create_realm", ctx): + _db.config.realms.append(realm) + _db.oidc[realm.rp_id] = OIDC(key=secret_key()) + + +def update_realm( + rp_id: str, + *, + rp_name: str | None = None, + auth_host: str | None = None, + origins: list[str] | None = None, + ctx: SessionContext | None = None, +) -> None: + """Update a realm's rp_name, auth_host and origins. + + The rp-id itself is immutable: credentials are stamped with it, so + changing it would orphan them โ€” delete and recreate the realm instead. + The caller must validate the resulting combined configuration. + """ + realm = _db.config.find_realm(rp_id) + if realm is None: + raise ValueError(f"Realm {rp_id} not found") + with _transaction("admin:update_realm", ctx): + realm.rp_name = rp_name + realm.auth_host = auth_host + realm.origins = origins + + +def delete_realm(rp_id: str, *, ctx: SessionContext | None = None) -> None: + """Delete a realm. Refused for the last realm or while credentials remain.""" + realm = _db.config.find_realm(rp_id) + if realm is None: + raise ValueError(f"Realm {rp_id} not found") + if len(_db.config.realms) <= 1: + raise ValueError("Cannot delete the last remaining realm") + if any(c.rp_id == rp_id for c in _db.credentials.values()): + raise ValueError( + f"Cannot delete realm {rp_id}: credentials still registered under it" + ) + with _transaction("admin:delete_realm", ctx): + _db.config.realms.remove(realm) + _db.oidc.pop(rp_id, None) + + # ------------------------------------------------------------------------- # OIDC Provider operations # ------------------------------------------------------------------------- -def create_oid_client(client: Client, *, ctx: SessionContext | None = None) -> None: - """Create a new OIDC client.""" - if client.uuid in _db.oidc.clients: +def create_oid_client( + rp_id: str, client: Client, *, ctx: SessionContext | None = None +) -> None: + """Create a new OIDC client under a realm.""" + provider = _oidc_provider(rp_id) + if client.uuid in provider.clients: raise ValueError(f"OIDC client {client.uuid} already exists") with _transaction("admin:create_oid_client", ctx): - _db.oidc.clients[client.uuid] = client + provider.clients[client.uuid] = client def update_oid_client( + rp_id: str, client_uuid: UUID, name: str | None = None, redirect_uris: list[str] | None = None, @@ -726,10 +797,11 @@ def update_oid_client( ctx: SessionContext | None = None, ) -> None: """Update an OIDC client's name, redirect URIs, and/or secret.""" - if client_uuid not in _db.oidc.clients: + provider = _oidc_provider(rp_id) + if client_uuid not in provider.clients: raise ValueError(f"OIDC client {client_uuid} not found") - client = _db.oidc.clients[client_uuid] + client = provider.clients[client_uuid] changes = {} if name is not None and name != client.name: @@ -766,19 +838,21 @@ def update_oid_client( backchannel_logout_uri=new_logout_uri, ) updated_client.uuid = client.uuid - _db.oidc.clients[client_uuid] = updated_client + provider.clients[client_uuid] = updated_client def reset_oid_client_secret( + rp_id: str, client_uuid: UUID, new_secret_hash: bytes, *, ctx: SessionContext | None = None, ) -> None: """Reset an OIDC client's secret.""" - if client_uuid not in _db.oidc.clients: + provider = _oidc_provider(rp_id) + if client_uuid not in provider.clients: raise ValueError(f"OIDC client {client_uuid} not found") - client = _db.oidc.clients[client_uuid] + client = provider.clients[client_uuid] with _transaction("admin:reset_oid_client_secret", ctx): updated = Client( client_secret_hash=new_secret_hash, @@ -787,12 +861,15 @@ def reset_oid_client_secret( backchannel_logout_uri=client.backchannel_logout_uri, ) updated.uuid = client.uuid - _db.oidc.clients[client_uuid] = updated + provider.clients[client_uuid] = updated -def delete_oid_client(client_uuid: UUID, *, ctx: SessionContext | None = None) -> None: +def delete_oid_client( + rp_id: str, client_uuid: UUID, *, ctx: SessionContext | None = None +) -> None: """Delete an OIDC client.""" - if client_uuid not in _db.oidc.clients: + provider = _oidc_provider(rp_id) + if client_uuid not in provider.clients: raise ValueError(f"OIDC client {client_uuid} not found") with _transaction("admin:delete_oid_client", ctx): - del _db.oidc.clients[client_uuid] + del provider.clients[client_uuid] diff --git a/paskia/db/paths.py b/paskia/db/paths.py index 09d9452..c63ca4d 100644 --- a/paskia/db/paths.py +++ b/paskia/db/paths.py @@ -1,47 +1,33 @@ -from __future__ import annotations +"""Filesystem paths for paskia persistence. + +The combined database is a single kanta JSONL file at the fixed +CWD-relative path ``paskia.kantadb``. Auxiliary user files (avatars) live +under ``paskia.data/``. The deployment is selected by the current working +directory; there is deliberately no environment override. +""" -import os -import shutil from pathlib import Path - -def db_root_path(*, rp_id: str = "localhost") -> Path: - """Return the configured persistence root directory.""" - return Path(os.environ.get("PASKIA_DB", f"{rp_id}.paskiadb")) +DB_FILENAME = "paskia.kantadb" +DATA_DIRNAME = "paskia.data" -def db_file_path(*, rp_id: str = "localhost", create_root: bool = False) -> Path: - """Return the JSONL database file path under the persistence root.""" - root = db_root_path(rp_id=rp_id) +def db_file_path() -> Path: + """Return the combined database file path.""" + return Path(DB_FILENAME) - if root.is_file(): - _migrate_legacy_db_file(root) +def data_root_path(create_root: bool = False) -> Path: + """Return the root directory for auxiliary files (avatars etc.).""" + root = Path(DATA_DIRNAME) if create_root: root.mkdir(parents=True, exist_ok=True) - - return root / "main.db" + return root -def users_root_path(*, rp_id: str = "localhost", create_root: bool = False) -> Path: +def users_root_path(create_root: bool = False) -> Path: """Return the filesystem root for persisted user files.""" - root = db_root_path(rp_id=rp_id) - - if root.is_file(): - _migrate_legacy_db_file(root) - + root = data_root_path(create_root=create_root) / "users" if create_root: root.mkdir(parents=True, exist_ok=True) - - return root / "users" - - -def _migrate_legacy_db_file(legacy_path: Path) -> None: - """Upgrade a legacy single-file database path into a directory root.""" - temp_root = legacy_path.parent / f".{legacy_path.name}.migrating" - shutil.rmtree(temp_root, ignore_errors=True) - temp_root.unlink(missing_ok=True) - - temp_root.mkdir(parents=True) - legacy_path.replace(temp_root / "main.db") - temp_root.rename(legacy_path) + return root diff --git a/paskia/db/structs.py b/paskia/db/structs.py index d9e11a0..34e392e 100644 --- a/paskia/db/structs.py +++ b/paskia/db/structs.py @@ -237,6 +237,12 @@ class User(msgspec.Struct, dict=True, omit_defaults=True, kw_only=True): """Get credential IDs for this user (for WebAuthn exclude lists).""" return [c.credential_id for c in self.credentials] + def credential_ids_for(self, rp_id: str) -> list[bytes]: + """Get credential IDs registered under a specific realm's rp-id.""" + return [ + c.credential_id for c in self.credentials if c.rp_id == rp_id + ] + @property def sessions(self) -> list[Session]: """Get all sessions for this user.""" @@ -290,8 +296,12 @@ class Credential(msgspec.Struct, dict=True): """Credential (passkey) data structure. Mutable fields: sign_count, last_used, last_verified - Immutable fields: credential_id, user, aaguid, public_key, created_at + Immutable fields: credential_id, user, aaguid, public_key, created_at, rp_id uuid is derived from created_at using uuid7. + + rp_id is the realm the passkey was registered under. With Related Origin + Requests it is always the realm's canonical rp-id, regardless of which + origin the registration ceremony ran on. """ credential_id: bytes # Long binary ID from the authenticator @@ -300,6 +310,7 @@ class Credential(msgspec.Struct, dict=True): public_key: bytes sign_count: int created_at: datetime + rp_id: str last_used: datetime | None = None last_verified: datetime | None = None @@ -341,6 +352,7 @@ class Credential(msgspec.Struct, dict=True): aaguid: UUID, public_key: bytes, sign_count: int, + rp_id: str, created_at: datetime | None = None, ) -> Credential: """Create a new Credential with auto-generated uuid7.""" @@ -353,6 +365,7 @@ class Credential(msgspec.Struct, dict=True): public_key=public_key, sign_count=sign_count, created_at=now, + rp_id=rp_id, last_used=now, last_verified=now, ) @@ -380,6 +393,8 @@ class Session(msgspec.Struct, dict=True, omit_defaults=True): user_agent: str validated: datetime client_uuid: UUID | None = msgspec.field(name="client", default=None) + rp_id: str | None = None # Owning realm (needed when no request context) + issuer: str | None = None # OIDC issuer URL this session was created under def __post_init__(self): if not hasattr(self, "key"): @@ -429,11 +444,15 @@ class Session(msgspec.Struct, dict=True, omit_defaults=True): user_agent: str, validated: datetime, client: UUID | None = None, + rp_id: str | None = None, + issuer: str | None = None, ) -> Session: """Create a new Session with the provided key. Args: key: The hashed session key (derived from secret via hash_secret) + rp_id: Owning realm's rp-id (used when no request context exists) + issuer: OIDC issuer URL (scheme + host) for OIDC sessions Returns: Session object with key set @@ -452,6 +471,8 @@ class Session(msgspec.Struct, dict=True, omit_defaults=True): user_agent=user_agent, validated=validated, client_uuid=client, + rp_id=rp_id, + issuer=issuer, ) session.key = key return session @@ -601,14 +622,42 @@ class OIDC(msgspec.Struct, dict=True): key: bytes | None = None -class Config(msgspec.Struct, omit_defaults=True): - """Stored configuration for the instance.""" +class RealmConfig(msgspec.Struct, omit_defaults=True): + """Configuration for one authentication realm (one WebAuthn rp-id). + + A realm is one rp-id with its associated hosts and origins. Origins may + be in the rp-id subtree (classic) or explicit related origins for + WebAuthn Related Origin Requests. + """ rp_id: str rp_name: str | None = None - auth_host: str | None = None - origins: list[str] | None = None - listen: list[str] | None = None + auth_host: str | None = None # This realm's dedicated auth host (URL) + origins: list[str] | None = None # Subdomain origins AND related origins + + +class Config(msgspec.Struct, omit_defaults=True): + """Stored configuration for the instance. + + Realms are shared by the whole administrative instance: organizations and + users are global across rp-ids. The first realm is the default realm, + used only where a default is genuinely needed (bootstrap reset-link URL, + startup display) โ€” never for request dispatch. + """ + + realms: list[RealmConfig] = msgspec.field( + default_factory=lambda: [RealmConfig(rp_id="localhost")] + ) + listen: list[str] | None = None # Process-global listen endpoints + + @property + def default_realm(self) -> RealmConfig: + """The first configured realm.""" + return self.realms[0] + + def find_realm(self, rp_id: str) -> RealmConfig | None: + """Find a realm configuration by rp-id.""" + return next((r for r in self.realms if r.rp_id == rp_id), None) # ------------------------------------------------------------------------- @@ -619,7 +668,7 @@ class Config(msgspec.Struct, omit_defaults=True): class DB(msgspec.Struct, dict=True, omit_defaults=False): """In-memory database. Access fields directly for reads.""" - config: Config = msgspec.field(default_factory=lambda: Config(rp_id="localhost")) + config: Config = msgspec.field(default_factory=Config) permissions: dict[UUID, Permission] = {} orgs: dict[UUID, Org] = {} roles: dict[UUID, Role] = {} @@ -627,8 +676,9 @@ class DB(msgspec.Struct, dict=True, omit_defaults=False): credentials: dict[UUID, Credential] = {} sessions: dict[str, Session] = {} reset_tokens: dict[str, ResetToken] = {} - # OIDC provider data - oidc: OIDC = msgspec.field(default_factory=lambda: OIDC()) + # OIDC provider data, keyed by realm rp-id: each realm is an independent + # issuer with its own signing key and clients. + oidc: dict[str, OIDC] = {} def __post_init__(self): # Optional store reference for non-global DB instances (e.g. tests). @@ -649,8 +699,13 @@ class DB(msgspec.Struct, dict=True, omit_defaults=False): for key, token in self.reset_tokens.items(): token.key = key # OIDC - for uuid, client in self.oidc.clients.items(): - client.uuid = uuid + for provider in self.oidc.values(): + for uuid, client in provider.clients.items(): + client.uuid = uuid + + def oidc_for(self, rp_id: str) -> OIDC | None: + """Get the OIDC provider data for a realm, if it exists.""" + return self.oidc.get(rp_id) def session_ctx( self, session_secret: str, host: str | None = None diff --git a/paskia/oidc_notify.py b/paskia/oidc_notify.py index 1c77fad..11dadb7 100644 --- a/paskia/oidc_notify.py +++ b/paskia/oidc_notify.py @@ -3,6 +3,10 @@ OIDC Back-Channel Logout notifications. When sessions are deleted (logout, admin, expiry), this module notifies any OIDC clients that have a backchannel_logout_uri configured. + +Notifications run without request context, so the realm and issuer come +from the session itself: ``Session.rp_id`` selects the realm's signing key +and ``Session.issuer`` (stamped at session creation/refresh) is the `iss`. """ import asyncio @@ -11,9 +15,8 @@ from uuid import UUID import httpx -from paskia import db +from paskia import db, realms from paskia.util import oidjwt -from paskia.util.runtime import config as runtime_config _logger = logging.getLogger(__name__) @@ -21,16 +24,23 @@ _logger = logging.getLogger(__name__) _TIMEOUT = httpx.Timeout(10.0, connect=5.0) -def _issuer() -> str: - """Derive issuer URL from config (same base as discovery document).""" - cfg = runtime_config() - return cfg.site_url if cfg else "https://localhost" +def _session_realm(rp_id: str | None): + """Resolve a session's realm, falling back to the default realm.""" + try: + reg = realms.registry() + except RuntimeError: + return None + if rp_id: + realm = reg.get(rp_id) + if realm is not None: + return realm + return reg.default def _collect_oidc_sessions( session_keys: list[str], -) -> list[tuple[str, str, UUID, UUID | None]]: - """Collect (backchannel_logout_uri, sid, client_uuid, user_uuid) for OIDC sessions. +) -> list[tuple[str, str, str, str, UUID, UUID | None]]: + """Collect (logout_uri, rp_id, issuer, sid, client_uuid, user_uuid). Must be called before the sessions are deleted from the database. Returns only sessions whose client has a backchannel_logout_uri configured. @@ -41,12 +51,23 @@ def _collect_oidc_sessions( session = data.sessions.get(key) if not session or session.client_uuid is None: continue - client = data.oidc.clients.get(session.client_uuid) + realm = _session_realm(session.rp_id) + if realm is None: + continue + provider = data.oidc.get(realm.rp_id) + client = provider.clients.get(session.client_uuid) if provider else None if not client or not client.backchannel_logout_uri: continue - sid = session.key + issuer = session.issuer or realm.site_url notifications.append( - (client.backchannel_logout_uri, sid, session.client_uuid, session.user_uuid) + ( + client.backchannel_logout_uri, + realm.rp_id, + issuer, + session.key, + session.client_uuid, + session.user_uuid, + ) ) return notifications @@ -77,22 +98,22 @@ async def _send_logout_token( async def notify( - notifications: list[tuple[str, str, UUID, UUID | None]], + notifications: list[tuple[str, str, str, str, UUID, UUID | None]], ) -> None: """Send back-channel logout tokens to all collected endpoints. Args: - notifications: list of (backchannel_logout_uri, sid, client_uuid, user_uuid) - as returned by _collect_oidc_sessions. + notifications: list of (backchannel_logout_uri, rp_id, issuer, sid, + client_uuid, user_uuid) as returned by _collect_oidc_sessions. """ if not notifications: return - issuer = _issuer() async with httpx.AsyncClient(timeout=_TIMEOUT) as client: tasks = [] - for uri, sid, client_uuid, user_uuid in notifications: + for uri, rp_id, issuer, sid, client_uuid, user_uuid in notifications: token = oidjwt.create_logout_token( + rp_id, issuer=issuer, audience=str(client_uuid), sid=sid, diff --git a/paskia/realms.py b/paskia/realms.py new file mode 100644 index 0000000..847bb23 --- /dev/null +++ b/paskia/realms.py @@ -0,0 +1,306 @@ +"""Realm registry: per-rp-id runtime state and host resolution. + +A **realm** is one rp-id with its associated hosts and origins. The +registry is built from the stored combined ``Config`` at startup and +rebuilt on admin realm changes; request dispatch resolves hosts to realms +through it. The database itself is global โ€” only the *current realm* +(passkey, site URLs, OIDC view) varies per request, tracked via a +contextvar set by the dispatch middleware. +""" + +from __future__ import annotations + +import contextvars +import os +from urllib.parse import urlparse + +from fastapi_vue.hostutil import parse_endpoints + +from paskia.db.structs import Config, RealmConfig +from paskia.util import hostutil +from paskia.util.constants import DEFAULT_PORT + +# Maximum number of related (non-subdomain) origins per realm. WebAuthn +# Related Origin Requests require browsers to support at least 5 labels. +DEFAULT_RELATED_ORIGIN_CAP = 5 + + +class Realm: + """Runtime view of one realm: stored config plus derived values.""" + + def __init__(self, config: RealmConfig, site_url: str, site_path: str): + # Lazy import: paskia.sansio depends on paskia.db, which (via + # paskia.db.operations โ†’ paskia.oidc_notify) depends on this module. + from paskia.sansio import Passkey + + self.config = config + self.site_url = site_url + self.site_path = site_path + self.passkey = Passkey( + rp_id=config.rp_id, + rp_name=config.rp_name, + origins=config.origins, + ) + + @property + def rp_id(self) -> str: + return self.config.rp_id + + @property + def rp_name(self) -> str: + return self.passkey.rp_name + + @property + def own_auth_host(self) -> str | None: + """This realm's own auth host as host[:port], if configured.""" + if not self.config.auth_host: + return None + return hostutil.auth_host_netloc(self.config.auth_host) + + @property + def related_origins(self) -> list[str]: + """Configured origins outside the rp-id subtree (ROR origins).""" + related = [] + for origin in self.config.origins or []: + hostname = hostutil.origin_hostname(origin) + if hostname and not hostutil.is_subdomain(hostname, self.rp_id): + related.append(origin) + return related + + @property + def is_root_mode(self) -> bool: + """Whether this realm's UI lives at the site root (own auth host).""" + return self.config.auth_host is not None + + @property + def ui_base_path(self) -> str: + return "/" if self.is_root_mode else "/auth/" + + @property + def auth_site_url(self) -> str: + """Base URL of this realm's auth site UI.""" + return self.site_url + self.site_path + + def api_url(self, path: str = "") -> str: + """Return an absolute URL under the canonical /auth/api/ prefix.""" + if not path: + return f"{self.site_url}/auth/api/" + return f"{self.site_url}/auth/api/{path.lstrip('/')}" + + def reset_link_url(self, token: str) -> str: + """Generate a reset link URL for the given token on this realm.""" + return f"{self.auth_site_url}{token}" + + +class RealmRegistry: + """Resolved realms and host lookup tables.""" + + def __init__(self, realms: list[Realm]): + self._by_rp_id = {r.rp_id: r for r in realms} + self._auth_hosts: dict[str, Realm] = {} + self._related_hosts: dict[str, Realm] = {} + for realm in realms: + if own := realm.own_auth_host: + self._auth_hosts[hostutil.normalize_host(own) or own] = realm + for origin in realm.related_origins: + if hostname := hostutil.origin_hostname(origin): + self._related_hosts[hostname] = realm + + @property + def realms(self) -> list[Realm]: + """All realms, in configuration order (first is the default).""" + return list(self._by_rp_id.values()) + + @property + def default(self) -> Realm: + """The default realm (first in configuration order).""" + return next(iter(self._by_rp_id.values())) + + def get(self, rp_id: str) -> Realm | None: + return self._by_rp_id.get(rp_id) + + def effective_auth_host(self, realm: Realm) -> str | None: + """Auth host serving WS/restricted APIs for a realm: its own, or the + first configured auth host (in realm order) as a shared fallback. + + Returns host[:port] suitable for URL building, or None. + """ + if realm.own_auth_host: + return realm.own_auth_host + for candidate in self._by_rp_id.values(): + if candidate.own_auth_host: + return candidate.own_auth_host + return None + + def resolve(self, host: str | None) -> Realm | None: + """Resolve a request Host header to a realm. + + Order: exact rp-id โ†’ exact auth host โ†’ exact related-origin + hostname โ†’ longest-suffix rp-id. Unknown hosts return None. + """ + h = hostutil.normalize_host(host) + if not h: + return None + if realm := self._by_rp_id.get(h): + return realm + if realm := self._auth_hosts.get(h): + return realm + if realm := self._related_hosts.get(h): + return realm + best = None + for rp_id, realm in self._by_rp_id.items(): + if h.endswith(f".{rp_id}") and (best is None or len(rp_id) > len(best.rp_id)): + best = realm + return best + + +def validate_config( + config: Config, *, related_origin_cap: int = DEFAULT_RELATED_ORIGIN_CAP +) -> None: + """Validate a combined configuration cross-realm. Raises ValueError.""" + if not config.realms: + raise ValueError("At least one realm (rp-id) is required") + + rp_ids: set[str] = set() + auth_hosts: dict[str, str] = {} # normalized host -> owning rp_id + related_hosts: dict[str, str] = {} # hostname -> owning rp_id + + for realm in config.realms: + hostutil.validate_rp_id(realm.rp_id) + if realm.rp_id in rp_ids: + raise ValueError(f"Duplicate rp-id '{realm.rp_id}'") + rp_ids.add(realm.rp_id) + + if realm.auth_host: + hostutil.validate_auth_host(realm.auth_host, realm.rp_id) + hn = hostutil.normalize_host( + hostutil.auth_host_netloc(realm.auth_host) or "" + ) + if hn: + if hn in auth_hosts: + raise ValueError( + f"auth-host '{hn}' is configured for both " + f"'{auth_hosts[hn]}' and '{realm.rp_id}'" + ) + auth_hosts[hn] = realm.rp_id + + related = 0 + for origin in realm.origins or []: + hn = hostutil.origin_hostname(origin) + if not hn: + raise ValueError(f"Invalid origin URL: '{origin}'") + if hostutil.is_subdomain(hn, realm.rp_id): + continue # Classic subtree origin + related += 1 + if hn in related_hosts: + raise ValueError( + f"Related origin host '{hn}' is configured for both " + f"'{related_hosts[hn]}' and '{realm.rp_id}'" + ) + related_hosts[hn] = realm.rp_id + if related > related_origin_cap: + raise ValueError( + f"Realm '{realm.rp_id}' has {related} related origins " + f"(maximum {related_origin_cap})" + ) + + for hn, owner in auth_hosts.items(): + if hn in rp_ids: + raise ValueError(f"auth-host '{hn}' collides with an rp-id") + if hn in related_hosts: + raise ValueError( + f"auth-host '{hn}' collides with a related origin of " + f"realm '{related_hosts[hn]}'" + ) + + for hn, owner in related_hosts.items(): + if hn in rp_ids: + raise ValueError( + f"Related origin host '{hn}' collides with an rp-id" + ) + for other in rp_ids: + if other != owner and hostutil.is_subdomain(hn, other): + raise ValueError( + f"Related origin host '{hn}' of realm '{owner}' " + f"falls inside realm '{other}'" + ) + + +def _derive_site( + realm: RealmConfig, *, listen_port: int | None, vite_url: str | None +) -> tuple[str, str]: + """Compute a realm's site_url and site_path. + + Priority: auth_host > origins[0] > PASKIA_VITE_URL (localhost realm + only) > http://localhost:port (localhost realm) > https://rp-id. + """ + if realm.auth_host: + return realm.auth_host, "/" + if realm.origins: + return realm.origins[0], "/auth/" + if realm.rp_id == "localhost": + if vite_url: + return vite_url.rstrip("/"), "/auth/" + if listen_port: + return f"http://localhost:{listen_port}", "/auth/" + return f"https://{realm.rp_id}", "/auth/" + + +_registry: RealmRegistry | None = None +_listen: list[str] | None = None + + +def configure(*, listen: list[str] | None = None) -> None: + """Record process-global serve parameters for site URL derivation.""" + global _listen + _listen = listen + + +def build(config: Config) -> RealmRegistry: + """Validate and build a registry from a combined configuration.""" + validate_config(config) + endpoint = next(iter(parse_endpoints(_listen, DEFAULT_PORT)), {}) + vite_url = os.environ.get("PASKIA_VITE_URL") + realms = [ + Realm( + rc, + *_derive_site(rc, listen_port=endpoint.get("port"), vite_url=vite_url), + ) + for rc in config.realms + ] + return RealmRegistry(realms) + + +def init_registry(config: Config) -> RealmRegistry: + """Build and install the global registry from a combined configuration.""" + global _registry + _registry = build(config) + return _registry + + +def registry() -> RealmRegistry: + """Return the global registry (must be initialized).""" + if _registry is None: + raise RuntimeError("Realm registry is not initialized") + return _registry + + +_current_realm: contextvars.ContextVar[Realm | None] = contextvars.ContextVar( + "paskia_current_realm", default=None +) + + +def set_current_realm(realm: Realm | None) -> contextvars.Token: + return _current_realm.set(realm) + + +def reset_current_realm(token: contextvars.Token) -> None: + _current_realm.reset(token) + + +def current_realm() -> Realm: + """Return the request's realm, or the default realm without request context.""" + realm = _current_realm.get() + if realm is not None: + return realm + return registry().default diff --git a/paskia/sansio.py b/paskia/sansio.py index 8890726..2bce3d1 100644 --- a/paskia/sansio.py +++ b/paskia/sansio.py @@ -8,8 +8,6 @@ This module provides a unified interface for WebAuthn operations including: """ import json -import re -from urllib.parse import urlparse from uuid import UUID from webauthn import ( @@ -36,7 +34,8 @@ from webauthn.helpers.structs import ( UserVerificationRequirement, ) -from paskia.db import Credential +from paskia.db.structs import Credential +from paskia.util import hostutil class Passkey: @@ -56,20 +55,22 @@ class Passkey: rp_id: Your security domain (e.g. "example.com") rp_name: The relying party display name (e.g. "Example App"). May be shown in authenticators. origins: List of allowed origin URLs (e.g. ["https://app.example.com", "https://auth.example.com"]). - Each must be a subdomain or same as rp_id. If not provided, any subdomain of rp_id is allowed. + Origins may be subdomains of rp_id (classic) or explicit related + origins on unrelated domains (Related Origin Requests). + If not provided, any subdomain of rp_id is allowed. supported_pub_key_algs: List of supported COSE algorithms (default is EDDSA, ECDSA_SHA_256, RSASSA_PKCS1_v1_5_SHA_256). Raises: - ValueError: If any origin domain doesn't match or isn't a subdomain of rp_id. + ValueError: If rp_id is not a valid domain or an origin is malformed. """ self.rp_id = rp_id - self._validate_rp_id(rp_id) + hostutil.validate_rp_id(rp_id) self.rp_name = rp_name or rp_id self.allowed_origins: set[str] | None = None if origins: # Validate and deduplicate origins into a set for O(1) lookups for o in origins: - self._validate_origin(o, rp_id) + self._validate_origin_url(o) self.allowed_origins = set(origins) self.supported_pub_key_algs = supported_pub_key_algs or [ COSEAlgorithmIdentifier.EDDSA, @@ -77,37 +78,23 @@ class Passkey: COSEAlgorithmIdentifier.RSASSA_PKCS1_v1_5_SHA_256, ] - def _validate_rp_id(self, rp_id: str) -> None: - """Validate that rp_id is a valid domain name.""" - if not rp_id: - raise ValueError("rp_id cannot be empty") - # Allow localhost, or domain-like strings - if rp_id == "localhost": - return - # Regex for valid domain: letters, digits, hyphens, dots, but not starting/ending with hyphen, etc. - # Simplified: alphanumeric, dots, hyphens - if not re.match( - 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])?)*$", - rp_id, - ): - raise ValueError(f"rp_id '{rp_id}' is not a valid domain name") - - def _validate_origin(self, origin: str, rp_id: str) -> None: - """Validate an origin URL against the rp_id.""" - hostname = urlparse(origin).hostname - if not hostname: + @staticmethod + def _validate_origin_url(origin: str) -> None: + """Validate that an origin URL is well-formed (has a hostname).""" + if not hostutil.origin_hostname(origin): raise ValueError(f"Invalid origin URL: no hostname found in '{origin}'") - if hostname == rp_id or hostname.endswith(f".{rp_id}"): - return - - raise ValueError( - f"Origin domain '{hostname}' must be the same as or a subdomain of rp_id '{rp_id}'" - ) + def _origin_in_subtree(self, origin: str) -> bool: + """Check whether an origin's hostname is the rp-id or its subdomain.""" + hostname = hostutil.origin_hostname(origin) + return bool(hostname) and hostutil.is_subdomain(hostname, self.rp_id) def validate_origin(self, origin: str) -> str: """Validate that origin is allowed and return it. + An origin is valid if its hostname is in the rp-id subtree **or** it + is explicitly listed in the configured origins (related origins). + Args: origin: The origin URL to validate (from WebSocket request header) @@ -115,13 +102,14 @@ class Passkey: The validated origin URL Raises: - ValueError: If origin is not in the allowed list (when origins are configured) - or if origin is not a valid subdomain of rp_id + ValueError: If origin is neither in the rp-id subtree nor listed """ - self._validate_origin(origin, self.rp_id) - if self.allowed_origins is not None and origin not in self.allowed_origins: - raise ValueError(f"Origin '{origin}' is not in the allowed origins list") - return origin + self._validate_origin_url(origin) + if self._origin_in_subtree(origin): + return origin + if self.allowed_origins is not None and origin in self.allowed_origins: + return origin + raise ValueError(f"Origin '{origin}' is not allowed for rp_id '{self.rp_id}'") ### Registration Methods ### @@ -197,6 +185,7 @@ class Passkey: aaguid=UUID(registration.aaguid), public_key=registration.credential_public_key, sign_count=registration.sign_count, + rp_id=self.rp_id, ) ### Authentication Methods ### diff --git a/paskia/util/hostutil.py b/paskia/util/hostutil.py index 5577e42..c4d2421 100644 --- a/paskia/util/hostutil.py +++ b/paskia/util/hostutil.py @@ -1,56 +1,21 @@ -"""Utilities for determining the auth UI host and base URLs.""" +"""Utilities for host/origin normalization and validation.""" +import re from urllib.parse import urlparse, urlsplit -from paskia.util.runtime import clear_config_cache -from paskia.util.runtime import config as runtime_config +_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 _cfg(): - return runtime_config() - - -def is_root_mode() -> bool: - cfg = _cfg() - return cfg is not None and cfg.config.auth_host is not None - - -def dedicated_auth_host() -> str | None: - """Return configured auth_host netloc, or None.""" - cfg = _cfg() - auth_host = cfg.config.auth_host if cfg else None - if not auth_host: - return None - - parsed = urlparse(auth_host if "://" in auth_host else f"//{auth_host}") - return parsed.netloc or parsed.path or None - - -def ui_base_path() -> str: - return "/" if is_root_mode() else "/auth/" - - -def api_url(path: str = "") -> str: - """Return an absolute URL under the canonical /auth/api/ prefix.""" - cfg = _cfg() - base = cfg.site_url if cfg else "https://localhost" - if not path: - return f"{base}/auth/api/" - normalized = path.lstrip("/") - return f"{base}/auth/api/{normalized}" - - -def auth_site_url() -> str: - """Return the base URL for the auth site UI (computed at startup).""" - cfg = _cfg() - if cfg: - return cfg.site_url + cfg.site_path - return "https://localhost/auth/" - - -def reset_link_url(token: str) -> str: - """Generate a reset link URL for the given token.""" - return f"{auth_site_url()}{token}" +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 normalize_origin(origin: str) -> str: @@ -60,6 +25,11 @@ def normalize_origin(origin: str) -> str: return origin.rstrip("/") +def origin_hostname(origin: str) -> str | None: + """Extract the lowercase hostname from an origin URL, if well-formed.""" + 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(".") @@ -84,10 +54,16 @@ def validate_auth_host(auth_host: str, rp_id: str) -> None: ) +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_auth_host_and_origins( auth_host: str | None, origins: list[str] | None ) -> tuple[str | None, list[str] | None]: - """Normalize auth_host and origins, matching CLI startup behavior. + """Normalize auth_host and origins. - Adds https:// to auth_host if no scheme present, strips trailing slashes - Validates auth_host is a well-formed subdomain (caller provides rp_id via validate_auth_host) @@ -105,12 +81,8 @@ def normalize_auth_host_and_origins( return auth_host, origins -def reload_config() -> None: - clear_config_cache() - - def normalize_host(raw_host: str | None) -> str | None: - """Normalize a Host header, stripping port numbers for consistent matching.""" + """Normalize a Host header, stripping port numbers and trailing dots.""" if not raw_host: return None candidate = raw_host.strip() @@ -127,7 +99,7 @@ def normalize_host(raw_host: str | None) -> str | None: else: # Strip port from host:port netloc = netloc.rsplit(":", 1)[0] - return netloc.lower() or None + return netloc.lower().rstrip(".") or None def format_endpoint(ep: dict) -> str: diff --git a/paskia/util/oidjwt.py b/paskia/util/oidjwt.py index 1a0e55a..ec7adea 100644 --- a/paskia/util/oidjwt.py +++ b/paskia/util/oidjwt.py @@ -1,5 +1,8 @@ """ OIDC JWT utilities for signing ID tokens and serving JWKS. + +Each realm is an independent OIDC provider with its own signing key; +keys are cached per rp-id. """ import hashlib @@ -18,46 +21,50 @@ from paskia.util.crypto import ( secret_key, ) -# JWT signing key (loaded on first use) -_private_key = None -_public_key = None -_kid: str | None = None +# JWT signing keys (loaded on first use), keyed by realm rp-id +_keys: dict[str, tuple[object, object, str]] = {} -def _load_or_generate_key() -> None: - """Load existing Ed25519 key or generate a new one.""" - global _private_key, _public_key, _kid - +def _load_or_generate_key(rp_id: str) -> tuple[object, object, str]: + """Load a realm's Ed25519 key or generate and store a new one.""" data = db.data() + provider = data.oidc.get(rp_id) + if provider is None: + raise RuntimeError(f"No OIDC provider for realm {rp_id}") store = data._store if store is None: raise RuntimeError("Kanta store is not initialized") - if data.oidc.key is not None: - _private_key = public_key_from_secret(data.oidc.key) + if provider.key is not None: + private_key = public_key_from_secret(provider.key) else: raw_key = secret_key() with store.transaction("oidc_key"): - data.oidc.key = raw_key - _private_key = public_key_from_secret(raw_key) + provider.key = raw_key + private_key = public_key_from_secret(raw_key) - _public_key = _private_key.public_key() + public_key = private_key.public_key() # Generate kid from public key fingerprint - pub_der = get_public_key_der(_private_key) - _kid = generate_kid(pub_der) + kid = generate_kid(get_public_key_der(private_key)) + return private_key, public_key, kid -def _ensure_key() -> None: - """Ensure key is loaded.""" - if _private_key is None: - _load_or_generate_key() +def _ensure_key(rp_id: str) -> tuple[object, object, str]: + """Ensure a realm's key is loaded and return (private, public, kid).""" + if rp_id not in _keys: + _keys[rp_id] = _load_or_generate_key(rp_id) + return _keys[rp_id] -def get_jwks() -> dict: +def clear_key(rp_id: str) -> None: + """Drop a realm's cached key (realm deleted or key rotated).""" + _keys.pop(rp_id, None) + + +def get_jwks(rp_id: str) -> dict: """Get JWKS (JSON Web Key Set) for public key verification.""" - _ensure_key() - assert _public_key is not None + private_key, _, kid = _ensure_key(rp_id) # Ed25519 public key is 32 bytes raw - pub_bytes = get_public_key_raw(_private_key) + pub_bytes = get_public_key_raw(private_key) return { "keys": [ { @@ -65,7 +72,7 @@ def get_jwks() -> dict: "crv": "Ed25519", "use": "sig", "alg": "EdDSA", - "kid": _kid, + "kid": kid, "x": urlsafe_b64encode(pub_bytes).rstrip(b"=").decode("ascii"), } ] @@ -73,6 +80,7 @@ def get_jwks() -> dict: def create_id_token( + rp_id: str, issuer: str, subject: UUID, audience: str, # client_id @@ -89,6 +97,7 @@ def create_id_token( """Create a signed ID token (JWT). Args: + rp_id: Realm whose signing key to use issuer: Token issuer (site URL) subject: User UUID (sub claim) audience: Client ID (aud claim) @@ -105,8 +114,7 @@ def create_id_token( Returns: Signed JWT string """ - _ensure_key() - assert _private_key is not None + private_key, _, kid = _ensure_key(rp_id) now = datetime.now(UTC) payload: dict[str, object] = { "iss": issuer, @@ -132,10 +140,11 @@ def create_id_token( if auth_time: payload["auth_time"] = int(auth_time.timestamp()) - return jwt.encode(payload, _private_key, algorithm="EdDSA", headers={"kid": _kid}) + return jwt.encode(payload, private_key, algorithm="EdDSA", headers={"kid": kid}) def create_access_token( + rp_id: str, issuer: str, subject: UUID, audience: str, @@ -145,6 +154,7 @@ def create_access_token( """Create a signed access token (JWT) for userinfo endpoint. Args: + rp_id: Realm whose signing key to use issuer: Token issuer (site URL) subject: User UUID audience: Client ID @@ -154,8 +164,7 @@ def create_access_token( Returns: Signed JWT string """ - _ensure_key() - assert _private_key is not None + private_key, _, kid = _ensure_key(rp_id) now = datetime.now(UTC) payload: dict[str, object] = { "iss": issuer, @@ -165,15 +174,16 @@ def create_access_token( "iat": int(now.timestamp()), "exp": int((now + timedelta(seconds=expires_in)).timestamp()), } - return jwt.encode(payload, _private_key, algorithm="EdDSA", headers={"kid": _kid}) + return jwt.encode(payload, private_key, algorithm="EdDSA", headers={"kid": kid}) def decode_access_token( - token: str, issuer: str, audience: str | None = None + rp_id: str, token: str, issuer: str, audience: str | None = None ) -> dict | None: """Decode and verify an access token. Args: + rp_id: Realm whose key to verify with token: JWT string issuer: Expected issuer audience: Optional expected audience (client_id). If provided, aud claim must match. @@ -181,13 +191,12 @@ def decode_access_token( Returns: Decoded payload or None if invalid """ - _ensure_key() - assert _public_key is not None + _, public_key, _ = _ensure_key(rp_id) try: if audience is not None: return jwt.decode( token, - _public_key, + public_key, algorithms=["EdDSA"], issuer=issuer, audience=audience, @@ -195,7 +204,7 @@ def decode_access_token( return jwt.decode( token, - _public_key, + public_key, algorithms=["EdDSA"], issuer=issuer, options={"verify_aud": False}, @@ -205,6 +214,7 @@ def decode_access_token( def create_logout_token( + rp_id: str, issuer: str, audience: str, sid: str | None = None, @@ -216,6 +226,7 @@ def create_logout_token( either sid (session) or sub (user), or both. Args: + rp_id: Realm whose signing key to use issuer: Token issuer (site URL) audience: Client ID (aud claim) sid: Session ID (base64url-encoded) @@ -224,8 +235,7 @@ def create_logout_token( Returns: Signed JWT string """ - _ensure_key() - assert _private_key is not None + private_key, _, kid = _ensure_key(rp_id) now = datetime.now(UTC) payload: dict[str, object] = { "iss": issuer, @@ -241,4 +251,4 @@ def create_logout_token( payload["sid"] = sid if sub: payload["sub"] = str(sub) - return jwt.encode(payload, _private_key, algorithm="EdDSA", headers={"kid": _kid}) + return jwt.encode(payload, private_key, algorithm="EdDSA", headers={"kid": kid}) diff --git a/paskia/util/runtime.py b/paskia/util/runtime.py index 5d4e6d6..2d8ec72 100644 --- a/paskia/util/runtime.py +++ b/paskia/util/runtime.py @@ -1,75 +1,36 @@ -"""Runtime configuration utilities.""" +"""Runtime serve configuration (process-global parameters only). + +Realm configuration lives in the database (``Config.realms``); the +``PASKIA_CONFIG`` environment variable only carries the effective listen +endpoints so that child processes (uvicorn reload / workers) can derive +site URLs the same way the parent did. +""" import os from functools import lru_cache import msgspec -from paskia.db.structs import Config +class ServeConfig(msgspec.Struct): + """Process-global serve parameters.""" -class RuntimeConfig(msgspec.Struct): - """Runtime configuration for the Paskia authentication server. - - Wraps the db Config (CLI/stored settings) with computed runtime fields. - Serialized to PASKIA_CONFIG env var as JSON via msgspec. - """ - - config: Config # CLI/stored configuration to persist - site_url: str # Base URL without trailing path (e.g. https://example.com) - site_path: str # Path to auth UI: "/" if auth_host, else "/auth/" - save: bool = False # Whether to persist config to database + listen: list[str] | None = None @lru_cache(maxsize=1) -def _load_config() -> RuntimeConfig | None: - """Load RuntimeConfig from PASKIA_CONFIG env var.""" - config_json = os.getenv("PASKIA_CONFIG") - if not config_json: +def _load() -> ServeConfig | None: + raw = os.getenv("PASKIA_CONFIG") + if not raw: return None - - return msgspec.json.decode(config_json.encode(), type=RuntimeConfig) + return msgspec.json.decode(raw.encode(), type=ServeConfig) -def config() -> RuntimeConfig | None: - """Return cached runtime config loaded from PASKIA_CONFIG.""" - return _load_config() +def serve_config() -> ServeConfig | None: + """Return cached serve configuration loaded from PASKIA_CONFIG.""" + return _load() -def clear_config_cache() -> None: - """Clear cached runtime config; next config() call reloads from env.""" - _load_config.cache_clear() - - -def update_runtime_config(new_config: Config) -> None: - """Update the runtime configuration with a new Config and refresh the cache.""" - current_runtime = config() - if not current_runtime: - return # No runtime config to update - - # Recompute site_url and site_path based on new config - old_auth_host = current_runtime.config.auth_host - if new_config.auth_host: - site_url, site_path = new_config.auth_host, "/" - else: - site_path = "/auth/" - # Never derive site_url from a just-removed auth host - origins = [o for o in (new_config.origins or []) if o != old_auth_host] - if origins: - site_url = origins[0] - elif current_runtime.site_url != old_auth_host: - # Keep current site_url if it wasn't derived from the removed auth host - site_url = current_runtime.site_url - else: - site_url = f"https://{new_config.rp_id}" - - new_runtime = RuntimeConfig( - config=new_config, - site_url=site_url, - site_path=site_path, - save=current_runtime.save, - ) - os.environ["PASKIA_CONFIG"] = msgspec.json.encode(new_runtime).decode() - - # Clear the cache so next access loads the updated config - clear_config_cache() +def clear_cache() -> None: + """Clear cached serve configuration; next serve_config() reloads.""" + _load.cache_clear() diff --git a/paskia/util/startupbox.py b/paskia/util/startupbox.py index a0f45de..c06349f 100644 --- a/paskia/util/startupbox.py +++ b/paskia/util/startupbox.py @@ -14,7 +14,7 @@ from paskia.util.constants import DEFAULT_PORT, DEVMODE from paskia.util.hostutil import format_endpoint if TYPE_CHECKING: - from paskia.util.runtime import RuntimeConfig + from paskia.realms import RealmRegistry BOX_WIDTH = 60 # Inner width (excluding box chars) @@ -48,14 +48,18 @@ def bottom() -> str: return "โ”—" + "โ”" * (BOX_WIDTH + 2) + "โ”›\n" -def print_startup_config(runtime: RuntimeConfig) -> None: - """Print server configuration on startup.""" +def print_startup_config( + registry: RealmRegistry, listen: list[str] | None = None +) -> None: + """Print server configuration on startup (one section per realm).""" # Key graphic with yellow shading (bright for highlights, dark for body) y = YELLOW # Bright golden yellow for main body b = BRIGHT_YELLOW # Brightest yellow for highlights/edges w = BRIGHT_WHITE # Bold white for URL r = RESET + default = registry.default + lines = [top()] lines.append(line(f" {b}โ–„โ–„โ–„โ–„โ–„{r}")) lines.append(line(f"{b}โ–ˆ{y} {b}โ–ˆ{r} Paskia " + __version__)) @@ -63,43 +67,41 @@ def print_startup_config(runtime: RuntimeConfig) -> None: lines.append( line( f"{b}โ–ˆ{y} {b}โ–ˆ{y}โ–€โ–€โ–€โ–€{b}โ–ˆ{y}โ–€โ–€{b}โ–ˆ{y}โ–€โ–€{b}โ–ˆ{r} {w}" - + runtime.site_url - + runtime.site_path + + default.site_url + + default.site_path + r ) ) lines.append(line(f" {y}โ–€โ–€โ–€โ–€โ–€{r}")) - # Format auth host section - if runtime.config.auth_host: - lines.append(line(f"Auth Host: {runtime.config.auth_host}")) - # Show frontend URL if in dev mode if DEVMODE: lines.append(line(f"Dev Frontend: {os.environ.get('PASKIA_VITE_URL')}")) # Format listen endpoints (dev mode only uses the first endpoint) - endpoints = list(parse_endpoints(runtime.config.listen, DEFAULT_PORT)) + endpoints = list(parse_endpoints(listen, DEFAULT_PORT)) if DEVMODE: endpoints = endpoints[:1] # server.run reload=True uses only one parts = [format_endpoint(ep) for ep in endpoints] lines.append(line(f"Backend: {' '.join(parts)}")) - # Relying Party line (omit name if same as id) - rp_id = runtime.config.rp_id - rp_name = runtime.config.rp_name - suffix = f" ({rp_name})" if rp_name and rp_name != rp_id else "" - lines.append(line(f"Relying Party: {rp_id}{suffix}")) - - # Format origins section - allowed = runtime.config.origins - if allowed: - lines.append(line("Permitted Origins:")) - for origin in sorted(allowed): - lines.append(line(f" - {origin}")) - else: - lines.append(line(f"Origin: {rp_id} and all subdomains allowed")) + realms = registry.realms + for realm in realms: + # Realm line (omit name if same as id); mark the default realm + rp_name = realm.rp_name + suffix = f" ({rp_name})" if rp_name and rp_name != realm.rp_id else "" + header = "Realm: " if len(realms) > 1 else "Relying Party: " + lines.append(line(f"{header}{realm.rp_id}{suffix}")) + if len(realms) > 1: + lines.append(line(f" URL: {realm.site_url}{realm.site_path}")) + if realm.config.auth_host: + lines.append(line(f" Auth Host: {realm.config.auth_host}")) + if realm.config.origins: + for origin in sorted(realm.config.origins): + lines.append(line(f" Origin: {origin}")) + else: + lines.append(line(f" Origin: {realm.rp_id} and subdomains")) lines.append(bottom()) stderr.write("".join(lines)) -- 2.55.0 From f44bcc9dea4f97b41e0522088a5c3aa1691b24db Mon Sep 17 00:00:00 2001 From: Leo Vasanko Date: Sun, 6 Sep 2026 04:11:22 +0000 Subject: [PATCH 05/48] Realm dispatch, per-realm OIDC, realm-scoped credentials and admin realm API - DispatchMiddleware (outermost app middleware) resolves Host to a realm: HTTP 421 for unknown hosts, WS closed pre-accept (1008); cross-realm WS only via the origin realm's effective auth host. Current realm exposed via request.state.realm and the current_realm() contextvar. - Credentials and sessions are scoped by realm rp_id: authentication only matches credentials of the dispatched realm; sessions record rp_id. - Auth codes (OIDC and cookie exchange) are stamped with the issuing realm and verified at redemption; remote-auth permits mint the exchange code for the *requesting* device's realm. - OIDC provider state (clients, signing keys) is per realm; token, userinfo, keys and backchannel-logout endpoints use the dispatched realm; refresh re-stamps the session issuer. - /.well-known/webauthn serves the realm's related origins (ROR). - Admin /server-config replaced by /realms CRUD (validated cross-realm, registry rebuilt on change); permission domains may reference any realm's hosts or clients; /settings reports the realm's own vs effective auth host. - paskia.globals and the runtime-backed hostutil helpers are gone. --- paskia/authcode.py | 12 +- paskia/db/operations.py | 8 +- paskia/fastapi/admin/adminapp.py | 10 +- paskia/fastapi/admin/oidc_clients.py | 8 +- paskia/fastapi/admin/permissions.py | 21 +++- paskia/fastapi/admin/realms.py | 154 ++++++++++++++++++++++++++ paskia/fastapi/admin/server_config.py | 85 -------------- paskia/fastapi/admin/users.py | 3 +- paskia/fastapi/api.py | 18 +-- paskia/fastapi/auth_host.py | 11 +- paskia/fastapi/dispatch.py | 94 ++++++++++++++++ paskia/fastapi/mainapp.py | 48 +++++--- paskia/fastapi/oid.py | 42 +++++-- paskia/fastapi/remote.py | 13 ++- paskia/fastapi/user.py | 3 +- paskia/fastapi/ws.py | 20 ++-- paskia/fastapi/wschat.py | 20 ++-- paskia/fastapi/wsutil.py | 6 +- paskia/globals.py | 20 ---- paskia/remoteauth.py | 3 + paskia/util/apistructs.py | 22 +++- paskia/util/avatar.py | 5 +- 22 files changed, 448 insertions(+), 178 deletions(-) create mode 100644 paskia/fastapi/admin/realms.py delete mode 100644 paskia/fastapi/admin/server_config.py create mode 100644 paskia/fastapi/dispatch.py delete mode 100644 paskia/globals.py diff --git a/paskia/authcode.py b/paskia/authcode.py index 2031a4e..4d497a3 100644 --- a/paskia/authcode.py +++ b/paskia/authcode.py @@ -24,21 +24,31 @@ class OIDCCode(msgspec.Struct): """An OIDC authorization code pending token exchange. PKCE uses S256 only when provided (verified at token exchange). + rp_id binds the code to the realm it was issued in; the token + endpoint (dispatched by Host) must match. """ session_key: str created: datetime redirect_uri: str scope: str + rp_id: str nonce: str | None = None code_challenge: str | None = None class CookieCode(msgspec.Struct): - """A cookie exchange code for setting session cookie after WebSocket auth.""" + """A cookie exchange code for setting session cookie after WebSocket auth. + + rp_id binds the code to the realm it was issued in; the redemption + endpoint (dispatched by Host) must match. This is what allows a + remote-auth approver on one realm to mint a code for the requesting + device's realm without the code being usable on the wrong realm. + """ session_key: str created: datetime + rp_id: str # Separate stores for each code type diff --git a/paskia/db/operations.py b/paskia/db/operations.py index a0b363e..e5ac25b 100644 --- a/paskia/db/operations.py +++ b/paskia/db/operations.py @@ -464,6 +464,7 @@ def update_session( ip: str | None = None, user_agent: str | None = None, validated: datetime | None = None, + issuer: str | None = None, *, ctx: SessionContext | None = None, ) -> None: @@ -480,6 +481,8 @@ def update_session( s.user_agent = user_agent if validated is not None: s.validated = validated + if issuer is not None: + s.issuer = issuer def set_session_host(key: str, host: str, *, ctx: SessionContext | None = None) -> None: @@ -576,6 +579,7 @@ def login( ip: str, user_agent: str, duration: timedelta = SESSION_LIFETIME, + rp_id: str | None = None, ) -> str: """Update user/credential on login and create session in a single transaction. @@ -583,7 +587,7 @@ def login( - user.last_seen, user.visits - credential.sign_count, credential.last_used Creates: - - new session + - new session (stamped with rp_id when provided) Returns the generated session token. """ @@ -606,6 +610,7 @@ def login( ip=ip, user_agent=user_agent, validated=now, + rp_id=rp_id, ) user_str = str(user_uuid) with _transaction("login", user=user_str): @@ -679,6 +684,7 @@ def create_credential_session( ip=ip, user_agent=user_agent, validated=now, + rp_id=credential.rp_id, ) user_str = str(user_uuid) with _transaction("create_credential_session", user=user_str): diff --git a/paskia/fastapi/admin/adminapp.py b/paskia/fastapi/admin/adminapp.py index c3dbe4a..eed8fde 100644 --- a/paskia/fastapi/admin/adminapp.py +++ b/paskia/fastapi/admin/adminapp.py @@ -8,14 +8,15 @@ from paskia.fastapi.admin import ( oidc_clients, orgs, permissions, + realms as realms_admin, roles, - server_config, users, ) from paskia.fastapi.admin.errors import install_error_handlers from paskia.fastapi.front import frontend from paskia.fastapi.response import MsgspecResponse from paskia.fastapi.session import AUTH_COOKIE +from paskia.realms import current_realm from paskia.util import ( avatar, permutil, @@ -38,7 +39,7 @@ app.mount("/orgs", orgs.app) app.mount("/roles", roles.app) app.mount("/users", users.app) app.mount("/permissions", permissions.app) -app.mount("/server-config", server_config.app) +app.mount("/realms", realms_admin.app) def master_admin(ctx) -> bool: @@ -94,10 +95,11 @@ async def admin_info(request: Request, auth=AUTH_COOKIE): perms = db.data().permissions.values() if master_admin(ctx) else ctx.org.permissions perms_dict = {p.uuid: ApiPermission.from_db(p) for p in perms} - # OIDC Clients (master admin only) + # OIDC Clients (master admin only) โ€” the current realm's provider oidc_clients_dict = {} if master_admin(ctx): - clients = sorted(db.data().oidc.clients.values(), key=lambda c: c.uuid) + provider = db.data().oidc_for(current_realm().rp_id) + clients = sorted(provider.clients.values(), key=lambda c: c.uuid) if provider else [] sessions = db.data().sessions # Count active sessions per client client_session_counts = {} diff --git a/paskia/fastapi/admin/oidc_clients.py b/paskia/fastapi/admin/oidc_clients.py index 2061520..2430729 100644 --- a/paskia/fastapi/admin/oidc_clients.py +++ b/paskia/fastapi/admin/oidc_clients.py @@ -8,6 +8,7 @@ from paskia.db.structs import Client from paskia.fastapi import authz from paskia.fastapi.admin.errors import install_error_handlers from paskia.fastapi.session import AUTH_COOKIE +from paskia.realms import current_realm from paskia.util import permutil app = FastAPI(docs_url=None, redoc_url=None, openapi_url=None) @@ -83,7 +84,7 @@ async def admin_create_oidc_client( ) client.uuid = client_uuid - db.create_oid_client(client, ctx=ctx) + db.create_oid_client(current_realm().rp_id, client, ctx=ctx) return {"status": "ok", "client_id": str(client.uuid)} @@ -152,6 +153,7 @@ async def admin_update_oidc_client( try: db.update_oid_client( + current_realm().rp_id, client_uuid, name=name, redirect_uris=redirect_uris, @@ -201,7 +203,7 @@ async def admin_reset_oidc_client_secret( raise ValueError("secret_hash must be a SHA-256 hash (32 bytes)") try: - db.reset_oid_client_secret(client_uuid, secret_hash, ctx=ctx) + db.reset_oid_client_secret(current_realm().rp_id, client_uuid, secret_hash, ctx=ctx) except ValueError as e: raise HTTPException(status_code=404, detail=str(e)) @@ -230,7 +232,7 @@ async def admin_delete_oidc_client( ) try: - db.delete_oid_client(client_uuid, ctx=ctx) + db.delete_oid_client(current_realm().rp_id, client_uuid, ctx=ctx) except ValueError as e: raise HTTPException(status_code=404, detail=str(e)) diff --git a/paskia/fastapi/admin/permissions.py b/paskia/fastapi/admin/permissions.py index 434b34e..399978d 100644 --- a/paskia/fastapi/admin/permissions.py +++ b/paskia/fastapi/admin/permissions.py @@ -7,7 +7,7 @@ from paskia.db import Permission as PermDC from paskia.fastapi import authz from paskia.fastapi.admin.errors import install_error_handlers from paskia.fastapi.session import AUTH_COOKIE -from paskia.globals import passkey +from paskia.realms import registry from paskia.util import hostutil, permutil, querysafe app = FastAPI(docs_url=None, redoc_url=None, openapi_url=None) @@ -16,23 +16,32 @@ install_error_handlers(app) def _validate_permission_domain(domain: str | None) -> None: - """Validate that domain is rp_id, a subdomain of it, or an OIDC client UUID.""" + """Validate that domain is a configured realm host or an OIDC client UUID. + + Accepted: any realm's rp-id or its subdomain, a related-origin hostname + of any realm, or the UUID of any realm's OIDC client (used for the + groups claim). + """ if domain is None: return # Allow OIDC client UUIDs (used for groups claim) try: client_uuid = UUID(domain) - if client_uuid in db.data().oidc.clients: + if any( + client_uuid in provider.clients + for provider in db.data().oidc.values() + ): return except ValueError: pass - rp_id = passkey.rp_id - if domain == rp_id or domain.endswith(f".{rp_id}"): + reg = registry() + if reg.resolve(domain) is not None: return raise ValueError( - f"Domain '{domain}' must be '{rp_id}', its subdomain, or an OIDC client UUID" + f"Domain '{domain}' must belong to a configured realm " + "or be an OIDC client UUID" ) diff --git a/paskia/fastapi/admin/realms.py b/paskia/fastapi/admin/realms.py new file mode 100644 index 0000000..78ce21b --- /dev/null +++ b/paskia/fastapi/admin/realms.py @@ -0,0 +1,154 @@ +"""Realm (rp-id) management API โ€” master admin only. + +Realms replace the old single-site server configuration: each realm is one +rp-id with its own rp-name, optional dedicated auth host, and origins +(including Related Origin Requests origins on unrelated domains). All +changes are validated cross-realm before being persisted, and the runtime +realm registry is rebuilt after each change so it takes effect immediately. +""" + +from fastapi import Body, FastAPI, Request + +from paskia import db, realms +from paskia.db.structs import Config, RealmConfig +from paskia.fastapi import authz +from paskia.fastapi.admin.errors import install_error_handlers +from paskia.fastapi.response import MsgspecResponse +from paskia.fastapi.session import AUTH_COOKIE +from paskia.util import hostutil, oidjwt +from paskia.util.apistructs import ApiRealm + +app = FastAPI(docs_url=None, redoc_url=None, openapi_url=None) + +install_error_handlers(app) + + +def _realm_to_api(realm: realms.Realm, registry: realms.RealmRegistry) -> ApiRealm: + return ApiRealm( + rp_id=realm.rp_id, + rp_name=realm.rp_name, + auth_host=realm.config.auth_host, + origins=list(realm.config.origins or []), + related_origins=realm.related_origins, + site_url=realm.site_url, + auth_site_url=realm.auth_site_url, + effective_auth_host=registry.effective_auth_host(realm), + is_default=realm is registry.default, + ) + + +def _normalize_realm_fields( + rp_id: str, auth_host: str | None, origins: list[str] | None +) -> tuple[str | None, list[str] | None]: + """Normalize and validate auth_host/origins for a realm (raises ValueError).""" + normalized_origins = [ + hostutil.normalize_origin(o.strip()) for o in origins or [] if o.strip() + ] or None + if auth_host: + hostutil.validate_auth_host(auth_host, rp_id) + return hostutil.normalize_auth_host_and_origins(auth_host, normalized_origins) + + +def _rebuild_registry() -> None: + """Rebuild the runtime realm registry from the stored configuration.""" + realms.init_registry(db.data().config) + + +@app.get("/") +async def admin_list_realms(request: Request, auth=AUTH_COOKIE): + """List all realms with derived URLs (master admin only).""" + await authz.verify(auth, ["auth:admin"], host=request.headers.get("host")) + registry = realms.registry() + return MsgspecResponse( + [_realm_to_api(realm, registry) for realm in registry.realms] + ) + + +@app.post("/") +async def admin_create_realm( + request: Request, + payload: dict = Body(...), + auth=AUTH_COOKIE, +): + """Add a new realm (master admin only, recent authentication required).""" + ctx = await authz.verify( + auth, ["auth:admin"], host=request.headers.get("host"), max_age="5m" + ) + + rp_id = (payload.get("rp_id") or "").strip().lower() + if not rp_id: + raise ValueError("rp_id is required") + rp_name = (payload.get("rp_name") or "").strip() or None + auth_host = (payload.get("auth_host") or "").strip() or None + auth_host, origins = _normalize_realm_fields( + rp_id, auth_host, payload.get("origins") or [] + ) + + config = db.data().config + new_realm = RealmConfig( + rp_id=rp_id, rp_name=rp_name, auth_host=auth_host, origins=origins + ) + # Validate the would-be combined configuration before persisting + realms.validate_config( + Config(realms=[*config.realms, new_realm], listen=config.listen) + ) + + db.create_realm(new_realm, ctx=ctx) + _rebuild_registry() + return {"status": "ok"} + + +@app.patch("/{rp_id}") +async def admin_update_realm( + rp_id: str, + request: Request, + payload: dict = Body(...), + auth=AUTH_COOKIE, +): + """Update a realm's rp_name, auth_host and origins (replaced wholesale). + + The rp-id itself is immutable: credentials are stamped with it. + """ + ctx = await authz.verify( + auth, ["auth:admin"], host=request.headers.get("host"), max_age="5m" + ) + + config = db.data().config + realm = config.find_realm(rp_id) + if realm is None: + raise ValueError(f"Realm {rp_id} not found") + + rp_name = (payload.get("rp_name") or "").strip() or None + auth_host = (payload.get("auth_host") or "").strip() or None + auth_host, origins = _normalize_realm_fields( + rp_id, auth_host, payload.get("origins") or [] + ) + + updated = RealmConfig( + rp_id=rp_id, rp_name=rp_name, auth_host=auth_host, origins=origins + ) + would_be = Config( + realms=[updated if r.rp_id == rp_id else r for r in config.realms], + listen=config.listen, + ) + realms.validate_config(would_be) + + db.update_realm(rp_id, rp_name=rp_name, auth_host=auth_host, origins=origins, ctx=ctx) + _rebuild_registry() + return {"status": "ok"} + + +@app.delete("/{rp_id}") +async def admin_delete_realm( + rp_id: str, + request: Request, + auth=AUTH_COOKIE, +): + """Delete a realm (refused for the last realm or while credentials remain).""" + ctx = await authz.verify( + auth, ["auth:admin"], host=request.headers.get("host"), max_age="5m" + ) + db.delete_realm(rp_id, ctx=ctx) + _rebuild_registry() + oidjwt.clear_key(rp_id) + return {"status": "ok"} diff --git a/paskia/fastapi/admin/server_config.py b/paskia/fastapi/admin/server_config.py deleted file mode 100644 index 79007a3..0000000 --- a/paskia/fastapi/admin/server_config.py +++ /dev/null @@ -1,85 +0,0 @@ -from fastapi import Body, FastAPI, HTTPException, Request - -from paskia import db -from paskia.db.structs import Config -from paskia.fastapi import authz -from paskia.fastapi.admin.errors import install_error_handlers -from paskia.fastapi.session import AUTH_COOKIE -from paskia.globals import passkey -from paskia.sansio import Passkey -from paskia.util import hostutil -from paskia.util.runtime import update_runtime_config - -app = FastAPI(docs_url=None, redoc_url=None, openapi_url=None) - -install_error_handlers(app) - - -@app.get("/") -async def admin_get_server_config( - request: Request, - auth=AUTH_COOKIE, -): - """Get current server configuration (master admin only).""" - await authz.verify(auth, ["auth:admin"], host=request.headers.get("host")) - pk = passkey - config = db.data().config - return { - "rp_name": pk.rp_name, - "auth_host": config.auth_host or "", - "origins": list(pk.allowed_origins) if pk.allowed_origins else [], - } - - -@app.patch("/") -async def admin_update_server_config( - request: Request, - payload: dict = Body(...), - auth=AUTH_COOKIE, -): - """Update server configuration (master admin only). - - Updates rp_name, auth_host, and origins in both the runtime Passkey - instance and the persisted database config. - """ - await authz.verify( - auth, ["auth:admin"], host=request.headers.get("host"), max_age="5m" - ) - config = db.data().config - pk = passkey - - rp_name = payload.get("rp_name", "").strip() or None - auth_host = payload.get("auth_host", "").strip() or None - raw_origins = payload.get("origins", []) - origins = [ - hostutil.normalize_origin(o.strip()) for o in raw_origins if o.strip() - ] or None - - # Normalize auth_host and origins (matching CLI startup behavior) - if auth_host: - try: - hostutil.validate_auth_host(auth_host, config.rp_id) - except ValueError as e: - raise HTTPException(status_code=400, detail=str(e)) - auth_host, origins = hostutil.normalize_auth_host_and_origins(auth_host, origins) - - # Validate origins against the current rp_id - if origins: - for o in origins: - Passkey(rp_id=config.rp_id, origins=[o]) # validates or raises - - # Update runtime Passkey instance - pk.rp_name = rp_name or config.rp_id - pk.allowed_origins = set(origins) if origins else None - - # Persist to database - new_config = Config( - rp_id=config.rp_id, - rp_name=rp_name, - auth_host=auth_host, - origins=origins, - listen=config.listen, - ) - db.update_config(new_config) - update_runtime_config(new_config) - return {"status": "ok"} diff --git a/paskia/fastapi/admin/users.py b/paskia/fastapi/admin/users.py index 7568146..06c2359 100644 --- a/paskia/fastapi/admin/users.py +++ b/paskia/fastapi/admin/users.py @@ -9,6 +9,7 @@ from paskia.fastapi import authz from paskia.fastapi.admin.errors import install_error_handlers from paskia.fastapi.response import MsgspecResponse from paskia.fastapi.session import AUTH_COOKIE +from paskia.realms import current_realm from paskia.util import avatar, hostutil, permutil from paskia.util.apistructs import ( ApiAaguidInfo, @@ -122,7 +123,7 @@ async def admin_create_user_registration_link( token_type=token_type, ctx=ctx, ) - url = hostutil.reset_link_url(token) + url = current_realm().reset_link_url(token) return MsgspecResponse( ApiCreateLinkResponse( url=url, diff --git a/paskia/fastapi/api.py b/paskia/fastapi/api.py index 9e3c3ee..5b6a6a0 100644 --- a/paskia/fastapi/api.py +++ b/paskia/fastapi/api.py @@ -20,7 +20,7 @@ from paskia.authsession import EXPIRES, get_reset, session_ctx from paskia.fastapi import authz, session, user from paskia.fastapi.response import MsgspecResponse from paskia.fastapi.session import AUTH_COOKIE, AUTH_COOKIE_NAME, get_client_ip -from paskia.globals import passkey as global_passkey +from paskia.realms import current_realm, registry from paskia.util import hostutil, htmlutil, passphrase, permutil, userinfo from paskia.util.apistructs import ( ApiCheckUserResponse, @@ -300,15 +300,15 @@ async def forward_authentication( @app.get("/settings") async def get_settings(): - pk = global_passkey - base_path = hostutil.ui_base_path() + realm = current_realm() return MsgspecResponse( ApiSettings( - rp_id=pk.rp_id, - rp_name=pk.rp_name, - ui_base_path=base_path, - auth_host=hostutil.dedicated_auth_host(), - auth_site_url=hostutil.auth_site_url(), + rp_id=realm.rp_id, + rp_name=realm.rp_name, + ui_base_path=realm.ui_base_path, + auth_host=registry().effective_auth_host(realm), + own_auth_host=realm.own_auth_host, + auth_site_url=realm.auth_site_url, session_cookie=AUTH_COOKIE_NAME, version=__version__, ), @@ -407,6 +407,8 @@ async def api_set_session( a = authcode.consume_cookie(auth.credentials) if not a: raise HTTPException(401, "Code expired or already used") + if a.rp_id != current_realm().rp_id: + raise HTTPException(401, "Code was issued for a different realm") secret = a.session_key diff --git a/paskia/fastapi/auth_host.py b/paskia/fastapi/auth_host.py index 1a8da01..6f62425 100644 --- a/paskia/fastapi/auth_host.py +++ b/paskia/fastapi/auth_host.py @@ -3,6 +3,7 @@ from fastapi import Request, Response from fastapi.responses import RedirectResponse +from paskia.realms import current_realm from paskia.util import hostutil, passphrase @@ -72,8 +73,14 @@ def redirect_to_root_on_auth_host(request: Request, cur: str, path: str) -> Resp async def redirect_middleware(request: Request, call_next): - """Middleware to handle auth host redirects.""" - cfg = hostutil.dedicated_auth_host() + """Middleware to handle auth host redirects. + + Only the current realm's *own* auth host triggers redirects; a realm + without one serves its UI under /auth/ on its own hosts. Realms + relying on a shared (fallback) auth host use it for WS/restricted + API calls, not for redirects. + """ + cfg = current_realm().own_auth_host if not cfg: return await call_next(request) diff --git a/paskia/fastapi/dispatch.py b/paskia/fastapi/dispatch.py new file mode 100644 index 0000000..0a384ee --- /dev/null +++ b/paskia/fastapi/dispatch.py @@ -0,0 +1,94 @@ +"""ASGI dispatch middleware: resolve the request Host to a realm. + +Every HTTP request and WebSocket connection is dispatched to exactly one +realm, resolved from the Host header via the realm registry. The resolved +realm is exposed as ``request.state.realm`` and through the +:func:`paskia.realms.current_realm` contextvar, which endpoint code uses +for all realm-dependent behavior (passkey configuration, OIDC provider, +site URLs). + +Unknown hosts are rejected before routing: + +- HTTP: ``421 Misdirected Request`` +- WebSocket: closed pre-accept with code 1008 + +For WebSocket connections the Origin header selects the realm when it +belongs to a different realm than the Host โ€” a related-origin page using +the realm's auth host, or a realm without its own auth host using the +shared one. A cross-realm connection is only allowed when the Host is the +origin realm's effective auth host; otherwise the connection is closed +pre-accept. When the Origin is missing or unknown the Host realm applies +and endpoint-side origin validation decides. +""" + +from fastapi.responses import PlainTextResponse + +from paskia import realms +from paskia.util import hostutil + +_WS_CLOSE_POLICY_VIOLATION = 1008 + + +def _header(scope: dict, name: str) -> str | None: + """Return the first value of a lowercased ASGI header name.""" + key = name.encode() + for header, value in scope.get("headers", []): + if header == key: + return value.decode() + return None + + +class DispatchMiddleware: + """Pure ASGI middleware dispatching each connection to its realm.""" + + def __init__(self, app): + self.app = app + + async def __call__(self, scope, receive, send): + if scope["type"] == "http": + await self._http(scope, receive, send) + elif scope["type"] == "websocket": + await self._websocket(scope, receive, send) + else: + await self.app(scope, receive, send) + + async def _http(self, scope, receive, send): + realm = realms.registry().resolve(_header(scope, "host")) + if realm is None: + response = PlainTextResponse("Unknown host", status_code=421) + await response(scope, receive, send) + return + await self._dispatch(scope, receive, send, realm) + + async def _websocket(self, scope, receive, send): + registry = realms.registry() + host = _header(scope, "host") + host_realm = registry.resolve(host) + if host_realm is None: + await send({"type": "websocket.close", "code": _WS_CLOSE_POLICY_VIOLATION}) + return + + realm = host_realm + origin = _header(scope, "origin") + origin_host = hostutil.origin_hostname(origin) if origin else None + origin_realm = registry.resolve(origin_host) if origin_host else None + if origin_realm is not None and origin_realm is not host_realm: + # Cross-realm connection: only via the origin realm's auth host. + effective = registry.effective_auth_host(origin_realm) + if not effective or hostutil.normalize_host(host) != hostutil.normalize_host( + effective + ): + await send( + {"type": "websocket.close", "code": _WS_CLOSE_POLICY_VIOLATION} + ) + return + realm = origin_realm + await self._dispatch(scope, receive, send, realm) + + async def _dispatch(self, scope, receive, send, realm: realms.Realm): + scope.setdefault("state", {})["realm"] = realm + token = realms.set_current_realm(realm) + try: + await self.app(scope, receive, send) + finally: + realms.reset_current_realm(token) diff --git a/paskia/fastapi/mainapp.py b/paskia/fastapi/mainapp.py index 55494c1..367c3d2 100644 --- a/paskia/fastapi/mainapp.py +++ b/paskia/fastapi/mainapp.py @@ -1,27 +1,26 @@ import asyncio import logging -import os from contextlib import asynccontextmanager from pathlib import Path -import msgspec from fastapi import FastAPI, HTTPException, Request, Response from fastapi.responses import FileResponse, RedirectResponse from kanta.logging import configure_logging as configure_kanta_logging -from paskia import authcode, db, remoteauth +from paskia import authcode, db, realms, remoteauth from paskia.bootstrap import bootstrap_if_needed from paskia.db.background import start_background, stop_background from paskia.db.lifecycle import kanta from paskia.fastapi import admin, api, auth_host, oid, ws from paskia.fastapi.admin.adminapp import adminapp +from paskia.fastapi.dispatch import DispatchMiddleware # Import frontend instance from paskia.fastapi.front import frontend from paskia.fastapi.session import AUTH_COOKIE -from paskia.util import hostutil, passphrase, vitedev +from paskia.util import passphrase, vitedev from paskia.util.constants import DEVMODE -from paskia.util.runtime import RuntimeConfig +from paskia.util.runtime import serve_config # Configure custom logging configure_kanta_logging() @@ -32,19 +31,22 @@ _EXAMPLES_DIR = Path(__file__).parent.parent.parent / "examples" @asynccontextmanager async def lifespan(app: FastAPI): # pragma: no cover - startup path - """Application lifespan to ensure globals (DB, passkey) are initialized in each process. + """Application lifespan: open the combined database and build the realm registry. - Configuration is passed via PASKIA_CONFIG JSON env variable (set by the CLI entrypoint) - so that uvicorn reload / multiprocess workers inherit the settings. - All keys are guaranteed to exist; values are already normalized by __main__.py. + Process-global serve parameters (listen endpoints) are passed via the + PASKIA_CONFIG JSON env variable (set by the CLI entrypoint) so that + uvicorn reload / multiprocess workers derive site URLs the same way. + Realm configuration is read from the database. """ - runtime = msgspec.json.decode(os.environ["PASKIA_CONFIG"], type=RuntimeConfig) + cfg = serve_config() + realms.configure(listen=cfg.listen if cfg else None) await asyncio.to_thread( Path(kanta.filename).parent.mkdir, parents=True, exist_ok=True ) async with kanta: try: + realms.init_registry(db.data().config) await remoteauth.init() await authcode.start() except ValueError as e: @@ -52,11 +54,7 @@ async def lifespan(app: FastAPI): # pragma: no cover - startup path # Re-raise to fail fast raise - # Bootstrap and persist config now that the full DB is loaded - await bootstrap_if_needed(config=runtime.config) - if runtime.save: - db.update_config(runtime.config) - + await bootstrap_if_needed() await frontend.load() await start_background() yield @@ -79,6 +77,10 @@ app = FastAPI( # Apply redirections to auth-host if configured (deny access to restricted endpoints, remove /auth/) app.middleware("http")(auth_host.redirect_middleware) +# Realm dispatch must be the outermost application middleware: everything +# below it (including the auth-host redirects) uses the current realm. +app.add_middleware(DispatchMiddleware) + app.mount("/auth/api/admin/", admin.app) app.mount("/auth/api/", api.app) app.mount("/auth/ws/", ws.app) @@ -124,6 +126,20 @@ async def openid_configuration(request: Request): } +@app.get("/.well-known/webauthn") +async def webauthn_related_origins(request: Request): + """WebAuthn Related Origin Requests discovery document. + + Served on the realm's rp-id site; lists the realm's related + (non-subdomain) origins that may assert this rp-id. 404 when the + realm has no related origins. + """ + related = request.state.realm.related_origins + if not related: + raise HTTPException(status_code=404) + return {"origins": related} + + @app.get("/auth/restricted/iframe") @app.get("/auth/restricted/oidc") async def restricted_view(request: Request): @@ -149,7 +165,7 @@ async def frontapp(request: Request, response: Response, auth=AUTH_COOKIE): @app.get("/admin", include_in_schema=False) @app.get("/auth/admin", include_in_schema=False) async def admin_root_redirect(): - return RedirectResponse(f"{hostutil.ui_base_path()}admin/", status_code=307) + return RedirectResponse(f"{realms.current_realm().ui_base_path}admin/", status_code=307) @app.get("/admin/", include_in_schema=False) diff --git a/paskia/fastapi/oid.py b/paskia/fastapi/oid.py index 12c8303..e600e23 100644 --- a/paskia/fastapi/oid.py +++ b/paskia/fastapi/oid.py @@ -21,7 +21,8 @@ from fastapi.responses import JSONResponse from fastapi.security import HTTPBearer from paskia import authcode, db -from paskia.db.structs import Session +from paskia.db.structs import OIDC, Session +from paskia.realms import current_realm from paskia.util import avatar, oidjwt from paskia.util.crypto import hash_secret @@ -30,10 +31,18 @@ _logger = logging.getLogger(__name__) app = FastAPI(docs_url=None, redoc_url=None, openapi_url=None) +def _provider() -> OIDC: + """Return the OIDC provider state of the current request's realm.""" + provider = db.data().oidc_for(current_realm().rp_id) + if provider is None: # pragma: no cover - invariant: realms always seed OIDC + raise RuntimeError(f"No OIDC provider for realm {current_realm().rp_id}") + return provider + + @app.get("/keys") async def keys(): """JSON Web Key Set for token verification.""" - return oidjwt.get_jwks() + return oidjwt.get_jwks(current_realm().rp_id) def _oidc_session_by_token( @@ -148,7 +157,7 @@ async def token( except ValueError: return JSONResponse({"error": "invalid_client"}, status_code=401) - client = db.data().oidc.clients.get(client_uuid) + client = _provider().clients.get(client_uuid) if not client or not client.verify_secret(client_secret): return JSONResponse({"error": "invalid_client"}, status_code=401) @@ -188,6 +197,16 @@ async def _handle_authorization_code( status_code=400, ) + # The code is bound to the realm it was issued in (dispatched by Host) + if oidc_code.rp_id != current_realm().rp_id: + return JSONResponse( + { + "error": "invalid_grant", + "error_description": "Code was issued for a different realm", + }, + status_code=400, + ) + # Look up the OIDC session by token session = _oidc_session_by_token(oidc_code.session_key, client.uuid) if not session: @@ -297,6 +316,7 @@ async def _handle_refresh_token( db.update_session( session.key, validated=now, + issuer=_get_issuer(request), ) _logger.info("OIDC session refreshed: %s", session.key) @@ -327,6 +347,7 @@ def _build_token_response( credential_uuid: UUID | None = None, ): """Build the token response with access_token, id_token, and refresh_token.""" + rp_id = current_realm().rp_id issuer = _get_issuer(request) # Get user's permissions scoped to this OIDC client (domain == client UUID) @@ -353,6 +374,7 @@ def _build_token_response( # Create ID token id_token = oidjwt.create_id_token( + rp_id, issuer=issuer, subject=user.uuid, audience=client_id, @@ -368,6 +390,7 @@ def _build_token_response( # Create access token access_token = oidjwt.create_access_token( + rp_id, issuer=issuer, subject=user.uuid, audience=client_id, @@ -401,8 +424,9 @@ async def userinfo( if not credentials: raise HTTPException(401, "Bearer token required") + rp_id = current_realm().rp_id issuer = _get_issuer(request) - payload = oidjwt.decode_access_token(credentials.credentials, issuer) + payload = oidjwt.decode_access_token(rp_id, credentials.credentials, issuer) if not payload: raise HTTPException(401, "Invalid or expired token") @@ -416,7 +440,7 @@ async def userinfo( except ValueError: raise HTTPException(401, "Invalid token (invalid aud format)") - if not db.data().oidc.clients.get(client_uuid): + if not _provider().clients.get(client_uuid): raise HTTPException(401, "Invalid token (unknown client)") # Get user @@ -486,8 +510,9 @@ async def backchannel_logout( ) # Decode and verify the logout token + rp_id = current_realm().rp_id issuer = _get_issuer(request) - payload = oidjwt.decode_access_token(logout_token, issuer) + payload = oidjwt.decode_access_token(rp_id, logout_token, issuer) if not payload: return JSONResponse( {"error": "invalid_request", "error_description": "Invalid logout_token"}, @@ -504,7 +529,7 @@ async def backchannel_logout( if aud: try: client_uuid = UUID(aud) - if not db.data().oidc.clients.get(client_uuid): + if not _provider().clients.get(client_uuid): return JSONResponse( { "error": "invalid_request", @@ -556,12 +581,13 @@ async def backchannel_logout( {"error": "invalid_request", "error_description": "Invalid sub claim"}, status_code=400, ) - # Find and delete matching sessions + # Find and delete matching sessions (this realm's OIDC sessions only) sessions_to_delete = [ s for s in db.data().sessions.values() if s.user_uuid == user_uuid and s.client_uuid is not None + and s.rp_id == rp_id and (client_uuid is None or s.client_uuid == client_uuid) ] for session in sessions_to_delete: diff --git a/paskia/fastapi/remote.py b/paskia/fastapi/remote.py index 33c2f19..a797396 100644 --- a/paskia/fastapi/remote.py +++ b/paskia/fastapi/remote.py @@ -22,6 +22,7 @@ from paskia.authsession import expires from paskia.fastapi.session import AUTH_COOKIE, infodict from paskia.fastapi.wschat import authenticate_and_login from paskia.fastapi.wsutil import validate_origin, websocket_error_handler +from paskia.realms import current_realm, registry from paskia.util import pow, useragent # Create a FastAPI subapp for remote auth WebSocket endpoints @@ -94,6 +95,7 @@ async def websocket_remote_auth_request(ws: WebSocket): host=host, ip=metadata.get("ip") or "", user_agent=metadata.get("user_agent") or "", + rp_id=current_realm().rp_id, action=action, ) @@ -333,10 +335,13 @@ async def websocket_remote_auth_permit(ws: WebSocket, auth=AUTH_COOKIE): ) # Create exchange code for the session (don't expose raw secret) + # Stamped with the *requesting* device's realm: it redeems the + # code on its own host, which dispatches to that realm. exchange_code = authcode.store_cookie( CookieCode( session_key=secret, created=datetime.now(UTC), + rp_id=request.rp_id, ) ) @@ -440,11 +445,17 @@ async def websocket_remote_auth_permit(ws: WebSocket, auth=AUTH_COOKIE): request.action = locked_action # Update local copy with locked value - # Send device info to the authenticating device + # Send device info to the authenticating device, including the + # requesting device's realm (may differ from the approver's) + requesting_realm = registry().get(request.rp_id) await ws.send_json( { "status": "found", "host": request.host, + "rp_id": request.rp_id, + "rp_name": ( + requesting_realm.rp_name if requesting_realm else request.rp_id + ), "user_agent_pretty": useragent.compact_user_agent( request.user_agent ), diff --git a/paskia/fastapi/user.py b/paskia/fastapi/user.py index 24b8521..f696abc 100644 --- a/paskia/fastapi/user.py +++ b/paskia/fastapi/user.py @@ -20,6 +20,7 @@ from paskia.authsession import ( from paskia.fastapi import authz, session from paskia.fastapi.response import MsgspecResponse from paskia.fastapi.session import AUTH_COOKIE +from paskia.realms import current_realm from paskia.util import avatar, hostutil from paskia.util.apistructs import ApiCreateLinkResponse @@ -291,7 +292,7 @@ async def api_create_link( token_type="device addition", ctx=ctx, ) - url = hostutil.reset_link_url(token) + url = current_realm().reset_link_url(token) return MsgspecResponse( ApiCreateLinkResponse( message="Registration link generated successfully", diff --git a/paskia/fastapi/ws.py b/paskia/fastapi/ws.py index 7fe010a..a164435 100644 --- a/paskia/fastapi/ws.py +++ b/paskia/fastapi/ws.py @@ -17,7 +17,7 @@ from paskia.fastapi.wschat import ( register_chat, ) from paskia.fastapi.wsutil import validate_origin, websocket_error_handler -from paskia.globals import passkey +from paskia.realms import current_realm from paskia.util import hostutil, passphrase from paskia.util.crypto import hash_secret @@ -28,6 +28,7 @@ def create_exchange_code(session_key: str) -> str: cookie_code = CookieCode( session_key=session_key, created=now, + rp_id=current_realm().rp_id, ) return authcode.store_cookie(cookie_code) @@ -55,10 +56,11 @@ async def websocket_register_add( """ origin = validate_origin(ws) host = hostutil.normalize_host(origin.split("://", 1)[1]) + realm = current_realm() if reset is not None: if not passphrase.is_well_formed(reset): raise ValueError( - f"The reset link for {passkey.rp_name} is invalid or has expired" + f"The reset link for {realm.rp_name} is invalid or has expired" ) s = get_reset(reset) user_uuid = s.user_uuid @@ -75,7 +77,7 @@ async def websocket_register_add( stripped = name.strip() if stripped: user_name = stripped - credential_ids = user.credential_ids or None + credential_ids = user.credential_ids_for(realm.rp_id) or None # WebAuthn registration credential = await register_chat(ws, user_uuid, user_name, origin, credential_ids) @@ -123,6 +125,7 @@ async def websocket_authenticate( ): origin = validate_origin(ws) host = origin.split("://", 1)[1] + realm = current_realm() # OIDC mode: validate client before auth oidc_client = None @@ -133,7 +136,7 @@ async def websocket_authenticate( await ws.send_json({"status": 400, "detail": "Invalid client_id"}) return - oidc_client = db.data().oidc.clients.get(client_uuid) + oidc_client = db.data().oidc_for(realm.rp_id).clients.get(client_uuid) if not oidc_client: await ws.send_json({"status": 400, "detail": "Unknown client_id"}) return @@ -145,9 +148,9 @@ async def websocket_authenticate( await ws.send_json({"status": 400, "detail": "Invalid redirect_uri"}) return # Store as the only allowed redirect URI - db.update_oid_client(client_uuid, redirect_uris=[redirect_uri]) + db.update_oid_client(realm.rp_id, client_uuid, redirect_uris=[redirect_uri]) # Reload client to get updated redirect_uris - oidc_client = db.data().oidc.clients.get(client_uuid) + oidc_client = db.data().oidc_for(realm.rp_id).clients.get(client_uuid) elif redirect_uri not in oidc_client.redirect_uris: await ws.send_json({"status": 400, "detail": "Invalid redirect_uri"}) return @@ -204,8 +207,6 @@ async def websocket_authenticate( cred, new_sign_count = await authenticate_chat(ws) # Get metadata for session - origin = validate_origin(ws) - host = origin.split("://", 1)[1] normalized_host = hostutil.normalize_host(host) metadata = infodict(ws, "oidc_auth") @@ -223,6 +224,8 @@ async def websocket_authenticate( user_agent=metadata["user_agent"], validated=now, client=oidc_client.uuid, + rp_id=realm.rp_id, + issuer=origin, ) db.oidc_login( session=session, @@ -235,6 +238,7 @@ async def websocket_authenticate( created=now, redirect_uri=redirect_uri, scope=scope, + rp_id=realm.rp_id, nonce=nonce, code_challenge=code_challenge, ) diff --git a/paskia/fastapi/wschat.py b/paskia/fastapi/wschat.py index 1f9ab04..9e3409f 100644 --- a/paskia/fastapi/wschat.py +++ b/paskia/fastapi/wschat.py @@ -11,7 +11,7 @@ from paskia.authsession import session_ctx from paskia.db import Credential, SessionContext from paskia.fastapi.session import infodict from paskia.fastapi.wsutil import validate_origin -from paskia.globals import passkey +from paskia.realms import current_realm, registry from paskia.util import hostutil @@ -23,6 +23,7 @@ async def register_chat( credential_ids: list[bytes] | None = None, ): """Run WebAuthn registration flow and return the verified credential.""" + passkey = current_realm().passkey options, challenge = passkey.reg_generate_options( user_id=user_uuid, user_name=user_name, @@ -42,6 +43,8 @@ async def authenticate_chat( Returns: tuple of (credential, new_sign_count) where new_sign_count comes from WebAuthn verification """ + realm = current_realm() + passkey = realm.passkey origin = validate_origin(ws) options, challenge = passkey.auth_generate_options(credential_ids=credential_ids) await ws.send_json({"optionsJSON": options}) @@ -51,7 +54,7 @@ async def authenticate_chat( ( c for c in db.data().credentials.values() - if c.credential_id == authcred.raw_id + if c.credential_id == authcred.raw_id and c.rp_id == realm.rp_id ), None, ) @@ -77,22 +80,20 @@ async def authenticate_and_login( Args: ws: The WebSocket connection (used for WebAuthn and origin validation) auth: Existing session cookie for re-auth credential restriction - session_host: Override host for the new session (defaults to ws origin) + session_host: Override host for the new session (defaults to ws origin); + must belong to a configured realm session_ip: Override IP for the new session (defaults to ws client IP) session_user_agent: Override user-agent for the new session (defaults to ws headers) Returns: Tuple of (SessionContext for the authenticated session, session secret) """ + realm = current_realm() origin = validate_origin(ws) host = origin.split("://", 1)[1] normalized_host = hostutil.normalize_host(host) if not normalized_host: raise ValueError("Host required for session creation") - hostname = normalized_host.split(":")[0] - rp_id = passkey.rp_id - if not (hostname == rp_id or hostname.endswith(f".{rp_id}")): - raise ValueError(f"Host must be the same as or a subdomain of {rp_id}") metadata = infodict(ws, "auth") # Get credential IDs if restricting to a user's credentials @@ -100,7 +101,7 @@ async def authenticate_and_login( if auth: existing_ctx = session_ctx(auth, host) if existing_ctx: - credential_ids = existing_ctx.user.credential_ids or None + credential_ids = existing_ctx.user.credential_ids_for(realm.rp_id) or None cred, new_sign_count = await authenticate_chat(ws, credential_ids) @@ -112,6 +113,8 @@ async def authenticate_and_login( ) if not login_host: raise ValueError("Host required for session creation") + if session_host is not None and registry().resolve(login_host) is None: + raise ValueError(f"Host '{login_host}' does not belong to a configured realm") login_ip = session_ip if session_ip is not None else metadata["ip"] login_user_agent = ( session_user_agent if session_user_agent is not None else metadata["user_agent"] @@ -125,6 +128,7 @@ async def authenticate_and_login( host=login_host, ip=login_ip, user_agent=login_user_agent, + rp_id=realm.rp_id, ) # Fetch and return the full session context (using the same host the session was created with) diff --git a/paskia/fastapi/wsutil.py b/paskia/fastapi/wsutil.py index d547915..bc5ad6b 100644 --- a/paskia/fastapi/wsutil.py +++ b/paskia/fastapi/wsutil.py @@ -10,7 +10,7 @@ from fastapi import WebSocket, WebSocketDisconnect from webauthn.helpers.exceptions import InvalidAuthenticationResponse from paskia.fastapi import authz -from paskia.globals import passkey +from paskia.realms import current_realm from paskia.util import pow @@ -83,9 +83,9 @@ def validate_origin(ws: WebSocket) -> str: """Extract and validate origin from WebSocket request headers. Raises: - ValueError: If origin header is missing or not in allowed list + ValueError: If origin header is missing or not allowed in the current realm """ origin = ws.headers.get("origin") if not origin: raise ValueError("Origin header is required for WebSocket connections") - return passkey.validate_origin(origin) + return current_realm().passkey.validate_origin(origin) diff --git a/paskia/globals.py b/paskia/globals.py deleted file mode 100644 index c852698..0000000 --- a/paskia/globals.py +++ /dev/null @@ -1,20 +0,0 @@ -"""Global Passkey instance configured from PASKIA_CONFIG. - -The Passkey instance is created at import time using the runtime configuration -passed via the ``PASKIA_CONFIG`` environment variable. Other runtime setup -(remote auth, auth codes, bootstrap checks) is performed explicitly by the -FastAPI lifespan once the database is open. -""" - -from paskia.sansio import Passkey -from paskia.util import runtime - -runtime = runtime.config() -if runtime is None: - raise RuntimeError("PASKIA_CONFIG must be defined before importing paskia.globals") - -passkey = Passkey( - rp_id=runtime.config.rp_id, - rp_name=runtime.config.rp_name, - origins=runtime.config.origins, -) diff --git a/paskia/remoteauth.py b/paskia/remoteauth.py index 143d004..7dd0d45 100644 --- a/paskia/remoteauth.py +++ b/paskia/remoteauth.py @@ -39,6 +39,7 @@ class RemoteAuthRequest: host: str # The host where the session should be created ip: str # IP of the requesting device user_agent: str # User agent of the requesting device + rp_id: str # Realm of the requesting device (session/exchange codes are stamped with it) action: str = "login" # "login" or "register" locked: bool = False # True once the authenticating device has entered the code # Callback to notify the requesting device when auth completes @@ -113,6 +114,7 @@ class RemoteAuthManager: host: str, ip: str, user_agent: str, + rp_id: str, action: str = "login", ) -> tuple[str, datetime]: """Create a new remote auth request. @@ -143,6 +145,7 @@ class RemoteAuthManager: host=host, ip=ip, user_agent=user_agent, + rp_id=rp_id, action=action, ) diff --git a/paskia/util/apistructs.py b/paskia/util/apistructs.py index 5ce0ca0..1d952be 100644 --- a/paskia/util/apistructs.py +++ b/paskia/util/apistructs.py @@ -161,17 +161,37 @@ class ApiOrgResponse(msgspec.Struct, kw_only=True): class ApiSettings(msgspec.Struct): - """Settings response struct.""" + """Settings response struct (per the realm the request was dispatched to). + + auth_host is the realm's effective auth host (its own, or the shared + fallback of another realm); own_auth_host is set only when this realm + has its own dedicated auth host. + """ rp_id: str rp_name: str ui_base_path: str auth_host: str | None + own_auth_host: str | None auth_site_url: str session_cookie: str version: str +class ApiRealm(msgspec.Struct): + """Realm entry in the admin realm list response.""" + + rp_id: str + rp_name: str + auth_host: str | None + origins: list[str] + related_origins: list[str] + site_url: str + auth_site_url: str + effective_auth_host: str | None + is_default: bool + + class ApiTokenInfo(msgspec.Struct, omit_defaults=True): """Token info response struct.""" diff --git a/paskia/util/avatar.py b/paskia/util/avatar.py index 4c765d1..de80dca 100644 --- a/paskia/util/avatar.py +++ b/paskia/util/avatar.py @@ -46,7 +46,10 @@ def avatar_url(user_uuid: UUID) -> str | None: """Return the absolute public avatar URL for a user, or None.""" if not avatar_path(user_uuid).is_file(): return None - return hostutil.api_url(f"user/{user_uuid}/profile.webp") + # Lazy import: paskia.realms pulls in paskia.db, which is circular here. + from paskia.realms import current_realm + + return current_realm().api_url(f"user/{user_uuid}/profile.webp") def current_avatar_url(user_uuid: UUID) -> str | None: -- 2.55.0 From 33d3b889416a3e1b494f8d055a65b10f1147ab95 Mon Sep 17 00:00:00 2001 From: Leo Vasanko Date: Sun, 6 Sep 2026 04:28:35 +0000 Subject: [PATCH 06/48] Test suite for the realm architecture - conftest: bootstrap seeds a localhost realm Config; realm_registry fixture builds the runtime registry; avatar storage redirected to a per-test tmp dir; credentials/sessions stamped with the test realm. - test_cli rewritten for the init/serve split, incl. legacy adoption. - TestServerConfig replaced by TestRealms covering the realm CRUD API, cross-realm validation, delete guards and effective-auth-host fallback. - Avatar/OIDC tests updated for per-realm providers and realm-derived URLs; obsolete PASKIA_DB path tests removed. --- paskia/__main__.py | 19 +- paskia/bootstrap.py | 1 - paskia/db/bootstrap.py | 2 +- paskia/db/legacy.py | 2 +- paskia/db/lifecycle.py | 1 - paskia/db/structs.py | 4 +- paskia/fastapi/admin/adminapp.py | 8 +- paskia/fastapi/admin/oidc_clients.py | 4 +- paskia/fastapi/admin/permissions.py | 8 +- paskia/fastapi/admin/realms.py | 4 +- paskia/fastapi/dispatch.py | 6 +- paskia/fastapi/mainapp.py | 4 +- paskia/fastapi/user.py | 2 +- paskia/realms.py | 11 +- paskia/util/avatar.py | 5 +- tests/conftest.py | 84 ++++----- tests/test_admin.py | 230 ++++++++++++++++++----- tests/test_api.py | 32 ++-- tests/test_cli.py | 262 +++++++++++++++++---------- tests/test_user.py | 31 ---- 20 files changed, 436 insertions(+), 284 deletions(-) diff --git a/paskia/__main__.py b/paskia/__main__.py index eadabd0..25ef656 100644 --- a/paskia/__main__.py +++ b/paskia/__main__.py @@ -7,10 +7,8 @@ from pathlib import Path import msgspec from fastapi_vue import server -from fastapi_vue.hostutil import parse_endpoints from kanta import Kanta -from paskia._version import __version__ from paskia.db import legacy from paskia.db.bootstrap import bootstrap, log_reset_link from paskia.db.paths import db_file_path @@ -102,12 +100,13 @@ def cmd_init(args: argparse.Namespace) -> None: # Bootstrap-time naming and hosts apply to the default realm; # everything is editable via the admin interface afterwards. realm.rp_name = args.rp_name or None - origins = ( - [normalize_origin(o) for o in _split_multi(args.origins)] or None - ) + origins = [normalize_origin(o) for o in _split_multi(args.origins)] or None auth_host = args.auth_host or None if auth_host: - validate_auth_host(auth_host, rp_id) + try: + validate_auth_host(auth_host, rp_id) + except ValueError as e: + raise SystemExit(str(e)) from e realm.auth_host, realm.origins = normalize_auth_host_and_origins( auth_host, origins ) @@ -157,9 +156,7 @@ def cmd_serve(args: argparse.Namespace) -> None: if adopted: print(f"โœ… Converted legacy database to {db_path} (realm: {adopted})") if not db_path.exists(): - raise SystemExit( - f"Database {db_path} not found โ€” run 'paskia init' first." - ) + raise SystemExit(f"Database {db_path} not found โ€” run 'paskia init' first.") config = _load_stored_config(db_path) try: @@ -172,7 +169,9 @@ def cmd_serve(args: argparse.Namespace) -> None: registry = build_registry(config) # Pass process-global serve parameters to the server process(es) - os.environ["PASKIA_CONFIG"] = msgspec.json.encode(ServeConfig(listen=listen)).decode() + os.environ["PASKIA_CONFIG"] = msgspec.json.encode( + ServeConfig(listen=listen) + ).decode() startupbox.print_startup_config(registry, listen=listen) diff --git a/paskia/bootstrap.py b/paskia/bootstrap.py index 0d93afb..9ff8f19 100644 --- a/paskia/bootstrap.py +++ b/paskia/bootstrap.py @@ -94,4 +94,3 @@ async def bootstrap_if_needed() -> bool: """ await check_admin_credentials() return False - diff --git a/paskia/db/bootstrap.py b/paskia/db/bootstrap.py index 14f9057..fa0f434 100644 --- a/paskia/db/bootstrap.py +++ b/paskia/db/bootstrap.py @@ -9,7 +9,7 @@ from datetime import UTC, datetime import uuid7 from paskia.authsession import reset_expires -from paskia.db.structs import DB, Config, OIDC, Org, Permission, ResetToken, Role, User +from paskia.db.structs import DB, OIDC, Config, Org, Permission, ResetToken, Role, User from paskia.util.crypto import secret_key _reset_link_logger = logging.getLogger("paskia.reset_link") diff --git a/paskia/db/legacy.py b/paskia/db/legacy.py index 1050c9f..cb8d5a1 100644 --- a/paskia/db/legacy.py +++ b/paskia/db/legacy.py @@ -24,8 +24,8 @@ from kanta import Kanta from paskia.db.paths import db_file_path, users_root_path from paskia.db.structs import ( - OIDC, DB, + OIDC, Config, Credential, Org, diff --git a/paskia/db/lifecycle.py b/paskia/db/lifecycle.py index b8bb58a..4aedd86 100644 --- a/paskia/db/lifecycle.py +++ b/paskia/db/lifecycle.py @@ -19,7 +19,6 @@ import paskia.db.operations as _ops from paskia import oidc_notify from paskia.authsession import EXPIRES from paskia.db.paths import db_file_path -from paskia.db.structs import DB logger = logging.getLogger(__name__) diff --git a/paskia/db/structs.py b/paskia/db/structs.py index 34e392e..2c3d022 100644 --- a/paskia/db/structs.py +++ b/paskia/db/structs.py @@ -239,9 +239,7 @@ class User(msgspec.Struct, dict=True, omit_defaults=True, kw_only=True): def credential_ids_for(self, rp_id: str) -> list[bytes]: """Get credential IDs registered under a specific realm's rp-id.""" - return [ - c.credential_id for c in self.credentials if c.rp_id == rp_id - ] + return [c.credential_id for c in self.credentials if c.rp_id == rp_id] @property def sessions(self) -> list[Session]: diff --git a/paskia/fastapi/admin/adminapp.py b/paskia/fastapi/admin/adminapp.py index eed8fde..09c2201 100644 --- a/paskia/fastapi/admin/adminapp.py +++ b/paskia/fastapi/admin/adminapp.py @@ -8,10 +8,12 @@ from paskia.fastapi.admin import ( oidc_clients, orgs, permissions, - realms as realms_admin, roles, users, ) +from paskia.fastapi.admin import ( + realms as realms_admin, +) from paskia.fastapi.admin.errors import install_error_handlers from paskia.fastapi.front import frontend from paskia.fastapi.response import MsgspecResponse @@ -99,7 +101,9 @@ async def admin_info(request: Request, auth=AUTH_COOKIE): oidc_clients_dict = {} if master_admin(ctx): provider = db.data().oidc_for(current_realm().rp_id) - clients = sorted(provider.clients.values(), key=lambda c: c.uuid) if provider else [] + clients = ( + sorted(provider.clients.values(), key=lambda c: c.uuid) if provider else [] + ) sessions = db.data().sessions # Count active sessions per client client_session_counts = {} diff --git a/paskia/fastapi/admin/oidc_clients.py b/paskia/fastapi/admin/oidc_clients.py index 2430729..6d496be 100644 --- a/paskia/fastapi/admin/oidc_clients.py +++ b/paskia/fastapi/admin/oidc_clients.py @@ -203,7 +203,9 @@ async def admin_reset_oidc_client_secret( raise ValueError("secret_hash must be a SHA-256 hash (32 bytes)") try: - db.reset_oid_client_secret(current_realm().rp_id, client_uuid, secret_hash, ctx=ctx) + db.reset_oid_client_secret( + current_realm().rp_id, client_uuid, secret_hash, ctx=ctx + ) except ValueError as e: raise HTTPException(status_code=404, detail=str(e)) diff --git a/paskia/fastapi/admin/permissions.py b/paskia/fastapi/admin/permissions.py index 399978d..35e373b 100644 --- a/paskia/fastapi/admin/permissions.py +++ b/paskia/fastapi/admin/permissions.py @@ -28,10 +28,7 @@ def _validate_permission_domain(domain: str | None) -> None: # Allow OIDC client UUIDs (used for groups claim) try: client_uuid = UUID(domain) - if any( - client_uuid in provider.clients - for provider in db.data().oidc.values() - ): + if any(client_uuid in provider.clients for provider in db.data().oidc.values()): return except ValueError: pass @@ -40,8 +37,7 @@ def _validate_permission_domain(domain: str | None) -> None: if reg.resolve(domain) is not None: return raise ValueError( - f"Domain '{domain}' must belong to a configured realm " - "or be an OIDC client UUID" + f"Domain '{domain}' must belong to a configured realm or be an OIDC client UUID" ) diff --git a/paskia/fastapi/admin/realms.py b/paskia/fastapi/admin/realms.py index 78ce21b..be7292f 100644 --- a/paskia/fastapi/admin/realms.py +++ b/paskia/fastapi/admin/realms.py @@ -133,7 +133,9 @@ async def admin_update_realm( ) realms.validate_config(would_be) - db.update_realm(rp_id, rp_name=rp_name, auth_host=auth_host, origins=origins, ctx=ctx) + db.update_realm( + rp_id, rp_name=rp_name, auth_host=auth_host, origins=origins, ctx=ctx + ) _rebuild_registry() return {"status": "ok"} diff --git a/paskia/fastapi/dispatch.py b/paskia/fastapi/dispatch.py index 0a384ee..7081814 100644 --- a/paskia/fastapi/dispatch.py +++ b/paskia/fastapi/dispatch.py @@ -75,9 +75,9 @@ class DispatchMiddleware: if origin_realm is not None and origin_realm is not host_realm: # Cross-realm connection: only via the origin realm's auth host. effective = registry.effective_auth_host(origin_realm) - if not effective or hostutil.normalize_host(host) != hostutil.normalize_host( - effective - ): + if not effective or hostutil.normalize_host( + host + ) != hostutil.normalize_host(effective): await send( {"type": "websocket.close", "code": _WS_CLOSE_POLICY_VIOLATION} ) diff --git a/paskia/fastapi/mainapp.py b/paskia/fastapi/mainapp.py index 367c3d2..9fff2dd 100644 --- a/paskia/fastapi/mainapp.py +++ b/paskia/fastapi/mainapp.py @@ -165,7 +165,9 @@ async def frontapp(request: Request, response: Response, auth=AUTH_COOKIE): @app.get("/admin", include_in_schema=False) @app.get("/auth/admin", include_in_schema=False) async def admin_root_redirect(): - return RedirectResponse(f"{realms.current_realm().ui_base_path}admin/", status_code=307) + return RedirectResponse( + f"{realms.current_realm().ui_base_path}admin/", status_code=307 + ) @app.get("/admin/", include_in_schema=False) diff --git a/paskia/fastapi/user.py b/paskia/fastapi/user.py index f696abc..c87be84 100644 --- a/paskia/fastapi/user.py +++ b/paskia/fastapi/user.py @@ -21,7 +21,7 @@ from paskia.fastapi import authz, session from paskia.fastapi.response import MsgspecResponse from paskia.fastapi.session import AUTH_COOKIE from paskia.realms import current_realm -from paskia.util import avatar, hostutil +from paskia.util import avatar from paskia.util.apistructs import ApiCreateLinkResponse app = FastAPI(docs_url=None, redoc_url=None, openapi_url=None) diff --git a/paskia/realms.py b/paskia/realms.py index 847bb23..3324d1a 100644 --- a/paskia/realms.py +++ b/paskia/realms.py @@ -12,7 +12,6 @@ from __future__ import annotations import contextvars import os -from urllib.parse import urlparse from fastapi_vue.hostutil import parse_endpoints @@ -31,7 +30,7 @@ class Realm: def __init__(self, config: RealmConfig, site_url: str, site_path: str): # Lazy import: paskia.sansio depends on paskia.db, which (via # paskia.db.operations โ†’ paskia.oidc_notify) depends on this module. - from paskia.sansio import Passkey + from paskia.sansio import Passkey # noqa: PLC0415 self.config = config self.site_url = site_url @@ -149,7 +148,9 @@ class RealmRegistry: return realm best = None for rp_id, realm in self._by_rp_id.items(): - if h.endswith(f".{rp_id}") and (best is None or len(rp_id) > len(best.rp_id)): + if h.endswith(f".{rp_id}") and ( + best is None or len(rp_id) > len(best.rp_id) + ): best = realm return best @@ -215,9 +216,7 @@ def validate_config( for hn, owner in related_hosts.items(): if hn in rp_ids: - raise ValueError( - f"Related origin host '{hn}' collides with an rp-id" - ) + raise ValueError(f"Related origin host '{hn}' collides with an rp-id") for other in rp_ids: if other != owner and hostutil.is_subdomain(hn, other): raise ValueError( diff --git a/paskia/util/avatar.py b/paskia/util/avatar.py index de80dca..0f36ee8 100644 --- a/paskia/util/avatar.py +++ b/paskia/util/avatar.py @@ -10,7 +10,7 @@ from uuid import UUID from fastapi import HTTPException, UploadFile from paskia.db.paths import users_root_path -from paskia.util import hostutil +from paskia.realms import current_realm MAX_UPLOAD_BYTES = 10 * 1024 * 1024 @@ -46,9 +46,6 @@ def avatar_url(user_uuid: UUID) -> str | None: """Return the absolute public avatar URL for a user, or None.""" if not avatar_path(user_uuid).is_file(): return None - # Lazy import: paskia.realms pulls in paskia.db, which is circular here. - from paskia.realms import current_realm - return current_realm().api_url(f"user/{user_uuid}/profile.webp") diff --git a/tests/conftest.py b/tests/conftest.py index d55e74f..af2ab07 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -12,12 +12,12 @@ in the database to test authenticated endpoints. from __future__ import annotations import asyncio -import json import os import secrets import tempfile from collections.abc import AsyncGenerator from datetime import UTC, datetime, timedelta +from pathlib import Path from uuid import UUID import httpx @@ -25,22 +25,8 @@ import pytest import pytest_asyncio from kanta import Kanta -# Keep runtime initialization invariant aligned with production: -# db.lifecycle requires PASKIA_CONFIG at import time. -os.environ.setdefault( - "PASKIA_CONFIG", - json.dumps( - { - "config": {"rp_id": "localhost", "rp_name": "localhost"}, - "site_url": "http://localhost:4401", - "site_path": "/auth/", - "save": False, - } - ), -) - import paskia.db.operations as ops_db -from paskia import globals as paskia_globals +from paskia import realms from paskia.authsession import reset_expires from paskia.config import SESSION_LIFETIME from paskia.db import ( @@ -56,12 +42,15 @@ from paskia.db import ( ) from paskia.db.bootstrap import bootstrap from paskia.db.operations import DB -from paskia.db.structs import Session +from paskia.db.structs import Config, RealmConfig, Session from paskia.fastapi.mainapp import app from paskia.fastapi.session import AUTH_COOKIE_NAME -from paskia.sansio import Passkey +from paskia.util import avatar from paskia.util.crypto import hash_secret +TEST_RP_ID = "localhost" +TEST_LISTEN = ["localhost:4401"] + @pytest.fixture(scope="session") def event_loop(): @@ -71,6 +60,19 @@ def event_loop(): loop.close() +@pytest.fixture(autouse=True) +def _avatar_tmp_root(tmp_path, monkeypatch): + """Redirect avatar storage to a per-test temporary directory.""" + root = tmp_path / "users" + + def users_root(create_root: bool = False) -> Path: + if create_root: + root.mkdir(parents=True, exist_ok=True) + return root + + monkeypatch.setattr(avatar, "users_root_path", users_root) + + @pytest_asyncio.fixture(scope="function") async def test_db() -> AsyncGenerator[DB]: """Create a temporary JSONL database for testing using kanta. @@ -79,15 +81,11 @@ async def test_db() -> AsyncGenerator[DB]: - auth:admin and auth:org:admin permissions - A default organization with Administration role - An admin user with the Administration role + - The localhost realm configuration (with its OIDC provider) """ with tempfile.NamedTemporaryFile(suffix=".jsonl", delete=True) as f: db = DB() - kanta = Kanta( - f.name, - db, - migrations="paskia.db.migrations", - ) - kanta.ctx.rp_id = "test.example.com" + kanta = Kanta(f.name, db) # Register bootstrap callback so kanta seeds the empty DB during open() @kanta.bootstrap(action="bootstrap") @@ -96,6 +94,7 @@ async def test_db() -> AsyncGenerator[DB]: data, org_name="Test Organization", admin_name="Test Admin", + config=Config(realms=[RealmConfig(rp_id=TEST_RP_ID)]), ) await kanta.open() @@ -107,25 +106,10 @@ async def test_db() -> AsyncGenerator[DB]: @pytest_asyncio.fixture(scope="function") -async def passkey_instance() -> Passkey: - """Override the module-level passkey instance for testing.""" - pk = Passkey( - rp_id="localhost", - rp_name="Test RP", - origins=["http://localhost:4401"], - ) - original = { - "rp_id": paskia_globals.passkey.rp_id, - "rp_name": paskia_globals.passkey.rp_name, - "allowed_origins": paskia_globals.passkey.allowed_origins, - } - paskia_globals.passkey.rp_id = pk.rp_id - paskia_globals.passkey.rp_name = pk.rp_name - paskia_globals.passkey.allowed_origins = pk.allowed_origins - yield pk - paskia_globals.passkey.rp_id = original["rp_id"] - paskia_globals.passkey.rp_name = original["rp_name"] - paskia_globals.passkey.allowed_origins = original["allowed_origins"] +async def realm_registry(test_db: DB) -> realms.RealmRegistry: + """Install the realm registry built from the test database config.""" + realms.configure(listen=TEST_LISTEN) + return realms.init_registry(test_db.config) @pytest_asyncio.fixture(scope="function") @@ -192,6 +176,7 @@ async def test_credential(test_db: DB, test_user: User) -> Credential: aaguid=UUID("00000000-0000-0000-0000-000000000000"), public_key=os.urandom(64), sign_count=0, + rp_id=TEST_RP_ID, ) create_credential(credential) return credential @@ -206,6 +191,7 @@ async def regular_credential(test_db: DB, regular_user: User) -> Credential: aaguid=UUID("00000000-0000-0000-0000-000000000000"), public_key=os.urandom(64), sign_count=0, + rp_id=TEST_RP_ID, ) create_credential(credential) return credential @@ -247,15 +233,9 @@ async def reset_token(test_db: DB, test_user: User, test_credential: Credential) @pytest_asyncio.fixture(scope="function") async def client( - test_db: DB, passkey_instance: Passkey + test_db: DB, realm_registry: realms.RealmRegistry ) -> AsyncGenerator[httpx.AsyncClient]: - """Create an async test client for the FastAPI app. - - Note: We import the app inside the fixture to ensure globals are - initialized first. - """ - # Import app after globals are set - + """Create an async test client for the FastAPI app.""" transport = httpx.ASGITransport(app=app) async with httpx.AsyncClient( transport=transport, @@ -283,6 +263,7 @@ def create_test_session( ip: str = "127.0.0.1", user_agent: str = "pytest", duration: timedelta | None = None, + rp_id: str = TEST_RP_ID, ) -> tuple[str, str]: """Create a test session. Returns (key, token) tuple. @@ -309,6 +290,7 @@ def create_test_session( ip=ip, user_agent=user_agent, validated=now, + rp_id=rp_id, ) if session.key in ops_db._db.sessions: raise ValueError("Session already exists") diff --git a/tests/test_admin.py b/tests/test_admin.py index d169405..b7e85d6 100644 --- a/tests/test_admin.py +++ b/tests/test_admin.py @@ -22,7 +22,7 @@ import pytest import pytest_asyncio import uuid7 -from paskia import db +from paskia import db, realms from paskia.db import ( Credential, Org, @@ -37,10 +37,7 @@ from paskia.db import ( create_user, ) from paskia.db.operations import DB -from paskia.util import hostutil from paskia.util.crypto import hash_secret -from paskia.util.runtime import clear_config_cache -from paskia.util.runtime import config as runtime_config from tests.conftest import auth_headers, create_test_image_bytes, create_test_session # -------------------- Additional Fixtures -------------------- @@ -91,6 +88,7 @@ async def second_org_credential(test_db: DB, second_org_user: User) -> Credentia aaguid=UUID("00000000-0000-0000-0000-000000000000"), public_key=os.urandom(64), sign_count=0, + rp_id="localhost", ) create_credential(credential) return credential @@ -145,6 +143,7 @@ async def org_admin_credential(test_db: DB, org_admin_user: User) -> Credential: aaguid=UUID("00000000-0000-0000-0000-000000000000"), public_key=os.urandom(64), sign_count=0, + rp_id="localhost", ) create_credential(credential) return credential @@ -253,8 +252,6 @@ class TestAdminOrganizations: monkeypatch, ): """Admin org payload should include canonical avatar URLs for listed users.""" - monkeypatch.setenv("PASKIA_DB", str(tmp_path / "test-avatar-db.paskiadb")) - upload = await client.put( f"/auth/api/user/{test_user.uuid}/profile.webp", files={"file": ("avatar.webp", create_test_image_bytes(), "image/webp")}, @@ -948,8 +945,6 @@ class TestAdminUsersInOrg: monkeypatch, ): """Admin should be able to upload avatar for a managed user.""" - monkeypatch.setenv("PASKIA_DB", str(tmp_path / "test-admin-avatar-db.paskiadb")) - response = await client.put( f"/auth/api/user/{test_user.uuid}/profile.webp", files={"file": ("avatar.webp", create_test_image_bytes(), "image/webp")}, @@ -1794,21 +1789,13 @@ class TestOrgAdminAuthExceptions: assert response.status_code == 403 -class TestServerConfig: - """Tests for GET/PATCH /auth/api/admin/server-config/ runtime updates.""" - - @pytest.fixture(scope="function") - def restore_runtime_config(self): - """Restore PASKIA_CONFIG env and cache after a test mutates runtime.""" - original = os.environ["PASKIA_CONFIG"] - yield - os.environ["PASKIA_CONFIG"] = original - clear_config_cache() +class TestRealms: + """Tests for the realm management API (/auth/api/admin/realms/).""" async def _set_auth_host(self, client, session_token, test_user, test_credential): - """Configure an auth host via PATCH, as the admin UI would.""" + """Configure an auth host on the localhost realm, as the admin UI would.""" r = await client.patch( - "/auth/api/admin/server-config/", + "/auth/api/admin/realms/localhost", json={ "rp_name": "", "auth_host": "auth.localhost", @@ -1817,15 +1804,42 @@ class TestServerConfig: headers={**auth_headers(session_token), "Host": "localhost:4401"}, ) assert r.status_code == 200, r.text - assert db.data().config.auth_host == "https://auth.localhost" - assert hostutil.dedicated_auth_host() == "auth.localhost" - assert hostutil.auth_site_url() == "https://auth.localhost/" + realm_cfg = db.data().config.find_realm("localhost") + assert realm_cfg.auth_host == "https://auth.localhost" + realm = realms.registry().get("localhost") + assert realm.own_auth_host == "auth.localhost" + assert realm.auth_site_url == "https://auth.localhost/" # Session for requests coming from the auth host (sessions are host-bound) _, token = create_test_session( test_user.uuid, test_credential.uuid, host="auth.localhost" ) return {**auth_headers(token), "Host": "auth.localhost"} + @pytest.mark.asyncio + async def test_list_realms(self, client: httpx.AsyncClient, session_token: str): + r = await client.get( + "/auth/api/admin/realms/", + headers={**auth_headers(session_token), "Host": "localhost:4401"}, + ) + assert r.status_code == 200, r.text + data = r.json() + assert len(data) == 1 + realm = data[0] + assert realm["rp_id"] == "localhost" + assert realm["is_default"] is True + assert realm["auth_host"] is None + assert realm["site_url"] == "http://localhost:4401" + + @pytest.mark.asyncio + async def test_realms_require_master_admin( + self, client: httpx.AsyncClient, regular_session_token: str + ): + r = await client.get( + "/auth/api/admin/realms/", + headers={**auth_headers(regular_session_token), "Host": "localhost:4401"}, + ) + assert r.status_code in (401, 403) + @pytest.mark.asyncio async def test_remove_auth_host_updates_runtime( self, @@ -1833,16 +1847,15 @@ class TestServerConfig: session_token: str, test_user, test_credential, - restore_runtime_config, ): - """Removing auth_host must clear it from runtime config and URLs.""" + """Removing auth_host must clear it from runtime realm config and URLs.""" headers = await self._set_auth_host( client, session_token, test_user, test_credential ) # The dialog still lists the old auth host among origins, so it is sent back r = await client.patch( - "/auth/api/admin/server-config/", + "/auth/api/admin/realms/localhost", json={ "rp_name": "", "auth_host": "", @@ -1851,23 +1864,24 @@ class TestServerConfig: headers=headers, ) assert r.status_code == 200, r.text - assert db.data().config.auth_host is None + assert db.data().config.find_realm("localhost").auth_host is None - rt = runtime_config() - assert rt.config.auth_host is None - assert rt.site_path == "/auth/" - assert "auth.localhost" not in rt.site_url - assert hostutil.dedicated_auth_host() is None - assert "auth.localhost" not in hostutil.auth_site_url() + realm = realms.registry().get("localhost") + assert realm.own_auth_host is None + assert realm.ui_base_path == "/auth/" + # Site URL derivation is stateless: with the auth host removed, the + # first remaining origin becomes the site URL. + assert realm.auth_site_url == "https://auth.localhost/auth/" # GET and settings reflect the cleared state r = await client.get( - "/auth/api/admin/server-config/", + "/auth/api/admin/realms/", headers={**auth_headers(session_token), "Host": "localhost:4401"}, ) - assert r.json()["auth_host"] == "" + assert r.json()[0]["auth_host"] is None r = await client.get("/auth/api/settings") assert r.json()["auth_host"] is None + assert r.json()["own_auth_host"] is None assert r.json()["ui_base_path"] == "/auth/" # Middleware no longer redirects to the removed auth host @@ -1879,13 +1893,12 @@ class TestServerConfig: assert "auth.localhost" not in r.headers.get("location", "") @pytest.mark.asyncio - async def test_remove_auth_host_without_origins_falls_back_to_rp_id( + async def test_remove_auth_host_without_origins_falls_back( self, client: httpx.AsyncClient, session_token: str, test_user, test_credential, - restore_runtime_config, ): """With no origins left, site_url must not keep the removed auth host.""" headers = await self._set_auth_host( @@ -1893,14 +1906,145 @@ class TestServerConfig: ) r = await client.patch( - "/auth/api/admin/server-config/", + "/auth/api/admin/realms/localhost", json={"rp_name": "", "auth_host": "", "origins": []}, headers=headers, ) assert r.status_code == 200, r.text - rt = runtime_config() - assert rt.config.auth_host is None - assert rt.site_path == "/auth/" - assert "auth.localhost" not in rt.site_url - assert "auth.localhost" not in hostutil.auth_site_url() + realm = realms.registry().get("localhost") + assert realm.own_auth_host is None + assert realm.ui_base_path == "/auth/" + assert "auth.localhost" not in realm.site_url + assert "auth.localhost" not in realm.auth_site_url + + @pytest.mark.asyncio + async def test_create_and_delete_realm( + self, client: httpx.AsyncClient, session_token: str + ): + headers = {**auth_headers(session_token), "Host": "localhost:4401"} + r = await client.post( + "/auth/api/admin/realms/", + json={ + "rp_id": "example.com", + "rp_name": "Example", + "origins": ["https://app.example.com", "https://unrelated-site.com"], + }, + headers=headers, + ) + assert r.status_code == 200, r.text + + r = await client.get("/auth/api/admin/realms/", headers=headers) + realms_list = {realm["rp_id"]: realm for realm in r.json()} + assert set(realms_list) == {"localhost", "example.com"} + created = realms_list["example.com"] + assert created["rp_name"] == "Example" + assert created["is_default"] is False + assert created["related_origins"] == ["https://unrelated-site.com"] + + # OIDC provider seeded for the new realm + assert db.data().oidc_for("example.com") is not None + + r = await client.delete("/auth/api/admin/realms/example.com", headers=headers) + assert r.status_code == 200, r.text + assert db.data().config.find_realm("example.com") is None + assert realms.registry().get("example.com") is None + + @pytest.mark.asyncio + async def test_create_realm_validation( + self, client: httpx.AsyncClient, session_token: str + ): + headers = {**auth_headers(session_token), "Host": "localhost:4401"} + + # rp_id is required + r = await client.post("/auth/api/admin/realms/", json={}, headers=headers) + assert r.status_code == 400 + + # Duplicate rp-id + r = await client.post( + "/auth/api/admin/realms/", json={"rp_id": "localhost"}, headers=headers + ) + assert r.status_code == 400 + + # Invalid rp-id + r = await client.post( + "/auth/api/admin/realms/", json={"rp_id": "not a domain!"}, headers=headers + ) + assert r.status_code == 400 + + # auth-host must be a subdomain of the rp-id + r = await client.post( + "/auth/api/admin/realms/", + json={"rp_id": "example.com", "auth_host": "auth.other.com"}, + headers=headers, + ) + assert r.status_code == 400 + + # Related origin host may not collide across realms + r = await client.post( + "/auth/api/admin/realms/", + json={"rp_id": "example.com", "origins": ["https://shared-app.com"]}, + headers=headers, + ) + assert r.status_code == 200 + r = await client.post( + "/auth/api/admin/realms/", + json={"rp_id": "other.com", "origins": ["https://shared-app.com"]}, + headers=headers, + ) + assert r.status_code == 400 + + @pytest.mark.asyncio + async def test_delete_realm_guards( + self, client: httpx.AsyncClient, session_token: str, test_credential + ): + headers = {**auth_headers(session_token), "Host": "localhost:4401"} + + # Cannot delete the last realm + r = await client.delete("/auth/api/admin/realms/localhost", headers=headers) + assert r.status_code == 400 + + # Unknown realm + r = await client.delete("/auth/api/admin/realms/nope.com", headers=headers) + assert r.status_code == 400 + + # A realm with credentials still registered under it cannot be deleted + r = await client.post( + "/auth/api/admin/realms/", json={"rp_id": "example.com"}, headers=headers + ) + assert r.status_code == 200 + cred = Credential.create( + credential_id=secrets.token_bytes(32), + user=test_credential.user_uuid, + aaguid=UUID("00000000-0000-0000-0000-000000000000"), + public_key=secrets.token_bytes(64), + sign_count=0, + rp_id="example.com", + ) + create_credential(cred) + r = await client.delete("/auth/api/admin/realms/example.com", headers=headers) + assert r.status_code == 400 + + @pytest.mark.asyncio + async def test_effective_auth_host_fallback( + self, + client: httpx.AsyncClient, + session_token: str, + test_user, + test_credential, + ): + """A realm without its own auth host uses the shared one in settings.""" + headers = await self._set_auth_host( + client, session_token, test_user, test_credential + ) + r = await client.post( + "/auth/api/admin/realms/", json={"rp_id": "example.com"}, headers=headers + ) + assert r.status_code == 200 + + # Settings on the example.com host report the shared effective auth host + r = await client.get("/auth/api/settings", headers={"Host": "example.com"}) + assert r.status_code == 200 + assert r.json()["rp_id"] == "example.com" + assert r.json()["auth_host"] == "auth.localhost" + assert r.json()["own_auth_host"] is None diff --git a/tests/test_api.py b/tests/test_api.py index 70cd10b..51cfd79 100644 --- a/tests/test_api.py +++ b/tests/test_api.py @@ -18,12 +18,12 @@ from uuid import UUID import httpx import pytest -from paskia import authcode, db +from paskia import authcode, db, realms from paskia.authsession import EXPIRES from paskia.db import delete_session -from paskia.db.structs import Client +from paskia.db.structs import Client, Config, RealmConfig from paskia.fastapi.api import _REFRESH_INTERVAL -from paskia.util import avatar, hostutil, oidjwt, permutil +from paskia.util import avatar, oidjwt, permutil from paskia.util.crypto import hash_secret from paskia.util.passphrase import generate from tests.conftest import auth_headers, create_test_image_bytes, create_test_session @@ -42,7 +42,7 @@ class TestSettingsEndpoint: assert "rp_name" in data assert "session_cookie" in data assert data["rp_id"] == "localhost" - assert data["rp_name"] == "Test RP" + assert data["rp_name"] == "localhost" assert data["session_cookie"] == "__Host-paskia" @pytest.mark.asyncio @@ -69,16 +69,14 @@ class TestAvatarUrls: self, tmp_path, monkeypatch ): """Absolute avatar URLs should preserve /auth/api even with an auth host.""" - db_root = tmp_path / "test-avatar-db.paskiadb" - monkeypatch.setenv("PASKIA_DB", str(db_root)) - monkeypatch.setattr( - hostutil, - "api_url", - lambda path="": f"https://auth.zi.fi/auth/api/{path.lstrip('/')}", + realms.configure(listen=None) + realms.init_registry( + Config(realms=[RealmConfig(rp_id="zi.fi", auth_host="https://auth.zi.fi")]) ) - user_uuid = test_uuid = UUID("019c6831-84cf-7b88-b66c-c8165890b7c5") - path = db_root / "users" / str(test_uuid) / "profile.webp" + # The autouse avatar fixture redirects storage to tmp_path / "users" + user_uuid = UUID("019c6831-84cf-7b88-b66c-c8165890b7c5") + path = tmp_path / "users" / str(user_uuid) / "profile.webp" path.parent.mkdir(parents=True, exist_ok=True) path.write_bytes(b"RIFF1234WEBP") @@ -646,8 +644,6 @@ class TestUserInfoEndpoint: monkeypatch, ): """User info should include the canonical avatar URL when present.""" - monkeypatch.setenv("PASKIA_DB", str(tmp_path / "test-avatar-db.paskiadb")) - upload = await client.put( f"/auth/api/user/{test_user.uuid}/profile.webp", files={"file": ("avatar.webp", create_test_image_bytes(), "image/webp")}, @@ -676,8 +672,6 @@ class TestUserInfoEndpoint: monkeypatch, ): """Avatar route should honor If-None-Match for unchanged avatars.""" - monkeypatch.setenv("PASKIA_DB", str(tmp_path / "test-avatar-db.paskiadb")) - upload = await client.put( f"/auth/api/user/{test_user.uuid}/profile.webp", files={"file": ("avatar.webp", create_test_image_bytes(), "image/webp")}, @@ -714,8 +708,6 @@ class TestOidcUserInfoEndpoint: monkeypatch, ): """OIDC userinfo should expose picture when profile scope is granted.""" - monkeypatch.setenv("PASKIA_DB", str(tmp_path / "test-avatar-db.paskiadb")) - upload = await client.put( f"/auth/api/user/{test_user.uuid}/profile.webp", files={"file": ("avatar.webp", create_test_image_bytes(), "image/webp")}, @@ -733,9 +725,10 @@ class TestOidcUserInfoEndpoint: if store is None: raise RuntimeError("Test DB store is not initialized") with store.transaction("create_test_oidc_client"): - test_db.oidc.clients[oidc_client.uuid] = oidc_client + test_db.oidc["localhost"].clients[oidc_client.uuid] = oidc_client access_token = oidjwt.create_access_token( + "localhost", issuer="http://localhost:4401", subject=test_user.uuid, audience=str(oidc_client.uuid), @@ -776,6 +769,7 @@ class TestSetSessionEndpoint: authcode.CookieCode( session_key=session_token, created=datetime.now(UTC), + rp_id="localhost", ) ) response = await client.post( diff --git a/tests/test_cli.py b/tests/test_cli.py index ac8ac93..451f861 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -1,4 +1,9 @@ -"""Tests for the CLI entry point in paskia/__main__.py.""" +"""Tests for the CLI entry point in paskia/__main__.py. + +The CLI is split into ``paskia init`` (create the combined paskia.kantadb +with the initial realm(s)) and bare ``paskia`` (serve the stored realms, +adopting a lone legacy ``.paskiadb`` database if present). +""" from __future__ import annotations @@ -6,83 +11,88 @@ import asyncio import os import subprocess import sys -import tempfile from pathlib import Path -from typing import Any +import msgspec import pytest from kanta import Kanta -from paskia.__main__ import main -from paskia.db.structs import DB, Config -from paskia.util.runtime import clear_config_cache -from paskia.util.runtime import config as runtime_config +from paskia.__main__ import _load_stored_config, main +from paskia.db import legacy +from paskia.db.structs import Config +from paskia.util.runtime import ServeConfig, clear_cache @pytest.fixture -def cli_run(monkeypatch): - """Run the CLI main() with the given args and return the RuntimeConfig.""" +def run_cli(monkeypatch, tmp_path): + """Run the CLI main() in a temporary working directory. - def _run(*args: str, db_root: str | None = None) -> Any: - env = os.environ.copy() - if db_root is not None: - env["PASKIA_DB"] = db_root - monkeypatch.setattr(os, "environ", env) + Returns a callable; server.run and the startup box are stubbed out. + The returned dict records the server.run invocation (if any). + """ + monkeypatch.chdir(tmp_path) + calls: dict = {} + monkeypatch.setattr( + "fastapi_vue.server.run", + lambda app, **kw: calls.update({"app": app, **kw}), + ) + monkeypatch.setattr( + "paskia.util.startupbox.print_startup_config", lambda *a, **kw: None + ) + monkeypatch.setattr("logging.basicConfig", lambda **kw: None) + # Isolate environment mutations (PASKIA_CONFIG) from other tests + env = os.environ.copy() + env.pop("PASKIA_CONFIG", None) + env.pop("PASKIA_VITE_URL", None) + monkeypatch.setattr(os, "environ", env) + def _run(*args: str) -> dict: monkeypatch.setattr(sys, "argv", ["paskia", *args]) - monkeypatch.setattr("fastapi_vue.server.run", lambda *_args, **_kw: None) - monkeypatch.setattr( - "paskia.util.startupbox.print_startup_config", lambda _rt: None - ) - monkeypatch.setattr("logging.basicConfig", lambda **_kw: None) - - clear_config_cache() - main() - runtime = runtime_config() - clear_config_cache() - return runtime + clear_cache() + try: + main() + finally: + clear_cache() + return calls return _run -async def _write_config(db_path: Path, config: Config) -> None: - """Write a Config into a JSONL database file using Kanta. - - The initial root uses a different rp_id so the stored diff includes the - target rp_id (required because Config omits defaults when diffing). - """ - kanta = Kanta( - str(db_path), - DB(config=Config(rp_id="uninitialized.invalid")), - migrations="paskia.db.migrations", - ) - kanta.ctx.rp_id = config.rp_id - await kanta.open() - with kanta.transaction("test:write_config"): - kanta.data.config = config - await kanta.close() +def stored_config(tmp_path: Path) -> Config: + """Read back the stored combined configuration.""" + return _load_stored_config(tmp_path / "paskia.kantadb") -def write_config(db_path: Path, config: Config) -> None: - """Synchronous wrapper for _write_config.""" - asyncio.run(_write_config(db_path, config)) +def write_legacy_db(root: Path, config: legacy.LegacyConfig) -> Path: + """Create a legacy-format database directory .paskiadb/main.db.""" + src_dir = root / f"{config.rp_id}.paskiadb" + src_dir.mkdir() + db_file = src_dir / "main.db" + + async def _write() -> None: + kanta = Kanta(str(db_file), legacy.LegacyDB()) + await kanta.open() + with kanta.transaction("test:seed"): + kanta.data.config = config + await kanta.close() + + asyncio.run(_write()) + return src_dir -def test_cli_defaults(cli_run): - with tempfile.TemporaryDirectory() as tmp: - runtime = cli_run("--rp-id", "localhost", db_root=tmp) +def test_init_defaults(run_cli, tmp_path): + run_cli("init") - assert runtime.config.rp_id == "localhost" - assert runtime.config.rp_name is None - assert runtime.config.auth_host is None - assert runtime.config.origins is None - assert runtime.site_url == "http://localhost:4401" - assert runtime.site_path == "/auth/" - assert runtime.save is False + config = stored_config(tmp_path) + assert [r.rp_id for r in config.realms] == ["localhost"] + assert config.realms[0].rp_name is None + assert config.realms[0].auth_host is None + assert config.listen is None -def test_cli_explicit_options(cli_run): - runtime = cli_run( +def test_init_full_options(run_cli, tmp_path): + run_cli( + "init", "--rp-id", "example.com", "--rp-name", @@ -91,56 +101,101 @@ def test_cli_explicit_options(cli_run): "auth.example.com", "--origin", "https://app.example.com", + "--listen", + "4402", ) - assert runtime.config.rp_id == "example.com" - assert runtime.config.rp_name == "Example Corp" - assert runtime.config.auth_host == "https://auth.example.com" - assert runtime.config.origins == [ - "https://auth.example.com", - "https://app.example.com", - ] - assert runtime.site_url == "https://auth.example.com" - assert runtime.site_path == "/" + config = stored_config(tmp_path) + realm = config.realms[0] + assert realm.rp_id == "example.com" + assert realm.rp_name == "Example Corp" + assert realm.auth_host == "https://auth.example.com" + assert realm.origins == ["https://auth.example.com", "https://app.example.com"] + assert config.listen == ["4402"] -def test_cli_loads_stored_config(cli_run): - with tempfile.TemporaryDirectory() as tmp: - db_path = Path(tmp) / "main.db" - write_config( - db_path, - Config( - rp_id="example.com", - rp_name="Stored Name", - origins=["https://stored.example.com"], - ), - ) - runtime = cli_run("--rp-id", "example.com", db_root=tmp) +def test_init_multiple_rp_ids(run_cli, tmp_path): + run_cli("init", "--rp-id", "company.com,app.com", "--rp-id", "pro.com") - assert runtime.config.rp_name == "Stored Name" - assert runtime.config.origins == ["https://stored.example.com"] - assert runtime.site_url == "https://stored.example.com" + config = stored_config(tmp_path) + assert [r.rp_id for r in config.realms] == ["company.com", "app.com", "pro.com"] + assert config.default_realm.rp_id == "company.com" -def test_cli_overrides_stored_config(cli_run): - with tempfile.TemporaryDirectory() as tmp: - db_path = Path(tmp) / "main.db" - write_config(db_path, Config(rp_id="example.com", rp_name="Stored Name")) - runtime = cli_run( - "--rp-id", "example.com", "--rp-name", "Overridden", db_root=tmp - ) - - assert runtime.config.rp_name == "Overridden" - - -def test_cli_save_flag(cli_run): - runtime = cli_run("--save") - assert runtime.save is True - - -def test_cli_invalid_auth_host(cli_run): +def test_init_refuses_existing_database(run_cli): + run_cli("init") with pytest.raises(SystemExit): - cli_run("--rp-id", "example.com", "--auth-host", "notsub.example.org") + run_cli("init") + + +def test_init_refuses_legacy_database(run_cli, tmp_path): + write_legacy_db(tmp_path, legacy.LegacyConfig(rp_id="example.com")) + with pytest.raises(SystemExit): + run_cli("init") + + +def test_init_invalid_auth_host(run_cli): + with pytest.raises(SystemExit): + run_cli("init", "--rp-id", "example.com", "--auth-host", "notsub.example.org") + + +def test_serve_requires_database(run_cli): + with pytest.raises(SystemExit, match="paskia init"): + run_cli() + + +def test_serve_uses_stored_config(run_cli, tmp_path): + run_cli("init", "--rp-id", "example.com", "--rp-name", "Stored Name") + calls = run_cli() + + assert calls["app"] == "paskia.fastapi.mainapp:app" + assert calls["listen"] is None # stored listen (None) used + serve = msgspec.json.decode(os.environ["PASKIA_CONFIG"].encode(), type=ServeConfig) + assert serve.listen is None + + +def test_serve_listen_override_not_persisted(run_cli, tmp_path): + run_cli("init", "--listen", "4402") + calls = run_cli("--listen", "4403") + + assert calls["listen"] == ["4403"] + serve = msgspec.json.decode(os.environ["PASKIA_CONFIG"].encode(), type=ServeConfig) + assert serve.listen == ["4403"] + # Stored config keeps the original listen value + assert stored_config(tmp_path).listen == ["4402"] + + +def test_serve_adopts_legacy_database(run_cli, tmp_path): + src_dir = write_legacy_db( + tmp_path, legacy.LegacyConfig(rp_id="example.com", rp_name="Legacy Name") + ) + # Persisted user files move to the new data root + avatar = src_dir / "users" / "019c6831-84cf-7b88-b66c-c8165890b7c5" + avatar.mkdir(parents=True) + (avatar / "profile.webp").write_bytes(b"RIFF1234WEBP") + + run_cli() + + config = stored_config(tmp_path) + assert [r.rp_id for r in config.realms] == ["example.com"] + assert config.realms[0].rp_name == "Legacy Name" + # Legacy directory renamed aside, user files adopted + assert not src_dir.exists() + assert (tmp_path / "example.com.paskiadb.converted-bak").is_dir() + assert ( + tmp_path + / "paskia.data" + / "users" + / "019c6831-84cf-7b88-b66c-c8165890b7c5" + / "profile.webp" + ).read_bytes() == b"RIFF1234WEBP" + + +def test_serve_multiple_legacy_databases_abort(run_cli, tmp_path): + write_legacy_db(tmp_path, legacy.LegacyConfig(rp_id="one.com")) + write_legacy_db(tmp_path, legacy.LegacyConfig(rp_id="two.com")) + with pytest.raises(SystemExit, match="Multiple legacy"): + run_cli() def test_cli_help(): @@ -152,3 +207,14 @@ def test_cli_help(): ) assert result.returncode == 0 assert "Paskia authentication server" in result.stdout + + +def test_cli_init_help(): + result = subprocess.run( + [sys.executable, "-m", "paskia", "init", "--help"], + capture_output=True, + text=True, + check=False, + ) + assert result.returncode == 0 + assert "Bootstrap" in result.stdout diff --git a/tests/test_user.py b/tests/test_user.py index c5c5bca..44efff2 100644 --- a/tests/test_user.py +++ b/tests/test_user.py @@ -15,7 +15,6 @@ from urllib.parse import urlsplit import httpx import pytest -from paskia.db.paths import db_file_path, users_root_path from tests.conftest import auth_headers, create_test_image_bytes @@ -93,8 +92,6 @@ class TestUserAvatar: monkeypatch, ): """Uploading a WebP avatar should store and expose the canonical URL.""" - monkeypatch.setenv("PASKIA_DB", str(tmp_path / "test-avatar-db.paskiadb")) - upload_bytes = create_test_image_bytes() response = await client.put( @@ -138,8 +135,6 @@ class TestUserAvatar: monkeypatch, ): """Avatar uploads must already be browser-prepared WebP.""" - monkeypatch.setenv("PASKIA_DB", str(tmp_path / "test-avatar-db.paskiadb")) - response = await client.put( f"/auth/api/user/{test_user.uuid}/profile.webp", files={ @@ -165,8 +160,6 @@ class TestUserAvatar: monkeypatch, ): """Deleting avatar should clear the user avatar URL.""" - monkeypatch.setenv("PASKIA_DB", str(tmp_path / "test-avatar-db.paskiadb")) - await client.put( f"/auth/api/user/{test_user.uuid}/profile.webp", files={"file": ("avatar.webp", create_test_image_bytes(), "image/webp")}, @@ -203,30 +196,6 @@ class TestUserAvatar: assert response.status_code == 403 -def test_paskia_db_legacy_file_is_migrated_to_root_dir(tmp_path, monkeypatch): - legacy_path = tmp_path / "legacy.paskiadb" - legacy_bytes = b'{"v":0}\n' - legacy_path.write_bytes(legacy_bytes) - - monkeypatch.setenv("PASKIA_DB", str(legacy_path)) - - db_path = db_file_path(create_root=True) - - assert legacy_path.is_dir() - assert db_path == legacy_path / "main.db" - assert db_path.read_bytes() == legacy_bytes - - -def test_paskia_db_root_uses_users_directory(tmp_path, monkeypatch): - root_path = tmp_path / "instance-root" - monkeypatch.setenv("PASKIA_DB", str(root_path)) - - users_path = users_root_path(create_root=True) - - assert users_path == root_path / "users" - assert users_path.parent == root_path - - class TestUserLogoutAll: """Tests for POST /auth/api/user/logout-all""" -- 2.55.0 From cdabc5d9e668b9ee73d354a6d655bbbf34be3627 Mon Sep 17 00:00:00 2001 From: Leo Vasanko Date: Sun, 6 Sep 2026 04:33:08 +0000 Subject: [PATCH 07/48] Realm machinery tests: resolution, validation, dispatch, code binding, conversion - Registry resolve order (exact rp-id, auth host, related origin, longest suffix), port/trailing-dot normalization, unknown hosts. - Cross-realm validate_config: related-origin cap, auth-host/related collisions, related-inside-other-realm, auth-host vs rp-id. - ASGI dispatch: HTTP 421, realm in scope state, contextvar scoping and reset, WS pre-accept close and cross-realm effective-auth-host rule. - Auth codes bound to issuing realm (set-session and OIDC token). - Legacy conversion stamps credentials/sessions/OIDC with the rp-id. - OIDC key censoring in transaction logs; bootstrap default-realm caveat. --- tests/test_realms.py | 494 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 494 insertions(+) create mode 100644 tests/test_realms.py diff --git a/tests/test_realms.py b/tests/test_realms.py new file mode 100644 index 0000000..bdd971b --- /dev/null +++ b/tests/test_realms.py @@ -0,0 +1,494 @@ +"""Tests for the multi-realm machinery: registry resolution, config +validation, ASGI dispatch, realm binding of auth codes, legacy database +conversion, log censoring and bootstrap caveats. +""" + +from __future__ import annotations + +import asyncio +import os +from datetime import UTC, datetime +from uuid import UUID + +import httpx +import pytest +from kanta import Kanta + +from paskia import authcode, realms +from paskia.bootstrap import check_admin_credentials +from paskia.db import create_credential +from paskia.db.legacy import ( + LegacyConfig, + LegacyCredential, + LegacyDB, + LegacySession, + convert_legacy_database, +) +from paskia.db.lifecycle import format_log_uuid +from paskia.db.operations import DB +from paskia.db.structs import Client, Config, Credential, RealmConfig +from paskia.fastapi.dispatch import DispatchMiddleware + +# ------------------------------------------------------------------------- +# Registry construction helpers +# ------------------------------------------------------------------------- + + +def build_registry(*realm_configs: RealmConfig) -> realms.RealmRegistry: + """Build and install a registry from realm configs (listen unset).""" + realms.configure(listen=None) + return realms.init_registry(Config(realms=list(realm_configs))) + + +ROR_CONFIG = Config( + realms=[ + RealmConfig( + rp_id="company.com", + auth_host="https://auth.company.com", + origins=["https://auth.company.com", "https://app.com"], + ), + RealmConfig(rp_id="pro.com"), + ] +) + + +class StubApp: + """ASGI app recording the scope it was called with.""" + + def __init__(self): + self.scope = None + + async def __call__(self, scope, receive, send): + self.scope = scope + + +async def drive_ws(middleware: DispatchMiddleware, headers: list[tuple[bytes, bytes]]): + """Run a websocket scope through the middleware, capturing sent messages.""" + + async def receive(): + return {"type": "websocket.connect"} + + sent = [] + + async def send(message): + sent.append(message) + + stub = middleware.app + await middleware( + {"type": "websocket", "headers": headers, "path": "/"}, receive, send + ) + return stub, sent + + +async def drive_http( + middleware: DispatchMiddleware, headers: list[tuple[bytes, bytes]] +): + """Run an http scope through the middleware, capturing sent messages.""" + + async def receive(): + return {"type": "http.request", "body": b""} + + sent = [] + + async def send(message): + sent.append(message) + + stub = middleware.app + await middleware( + { + "type": "http", + "headers": headers, + "method": "GET", + "path": "/", + "query_string": b"", + }, + receive, + send, + ) + return stub, sent + + +# ------------------------------------------------------------------------- +# Host resolution +# ------------------------------------------------------------------------- + + +class TestResolve: + def test_exact_rp_id(self): + reg = build_registry(*ROR_CONFIG.realms) + assert reg.resolve("pro.com").rp_id == "pro.com" + assert reg.resolve("company.com").rp_id == "company.com" + + def test_auth_host_and_related_origin(self): + reg = build_registry(*ROR_CONFIG.realms) + assert reg.resolve("auth.company.com").rp_id == "company.com" + assert reg.resolve("app.com").rp_id == "company.com" + + def test_subdomain_suffix_longest_match(self): + reg = build_registry( + RealmConfig(rp_id="example.com"), RealmConfig(rp_id="sub.example.com") + ) + assert reg.resolve("www.example.com").rp_id == "example.com" + assert reg.resolve("api.sub.example.com").rp_id == "sub.example.com" + + def test_port_and_trailing_dot_normalized(self): + reg = build_registry(*ROR_CONFIG.realms) + assert reg.resolve("pro.com:8443").rp_id == "pro.com" + assert reg.resolve("app.com.").rp_id == "company.com" + + def test_unknown_host(self): + reg = build_registry(*ROR_CONFIG.realms) + assert reg.resolve("evil.com") is None + assert reg.resolve("") is None + assert reg.resolve(None) is None + + def test_effective_auth_host_fallback(self): + reg = build_registry(*ROR_CONFIG.realms) + company = reg.get("company.com") + pro = reg.get("pro.com") + assert reg.effective_auth_host(company) == "auth.company.com" + # pro.com has no own auth host: falls back to the first configured one + assert reg.effective_auth_host(pro) == "auth.company.com" + # No auth hosts at all: None + reg2 = build_registry(RealmConfig(rp_id="a.com"), RealmConfig(rp_id="b.com")) + assert reg2.effective_auth_host(reg2.get("a.com")) is None + + +# ------------------------------------------------------------------------- +# Cross-realm configuration validation +# ------------------------------------------------------------------------- + + +class TestValidateConfig: + def test_valid(self): + realms.validate_config(ROR_CONFIG) + + def test_related_origin_cap(self): + realms.validate_config( + Config( + realms=[ + RealmConfig( + rp_id="company.com", + origins=[f"https://app{i}.com" for i in range(5)], + ) + ] + ) + ) + with pytest.raises(ValueError, match="related origins"): + realms.validate_config( + Config( + realms=[ + RealmConfig( + rp_id="company.com", + origins=[f"https://app{i}.com" for i in range(6)], + ) + ] + ) + ) + + def test_auth_host_collision(self): + with pytest.raises(ValueError, match="collides with a related origin"): + realms.validate_config( + Config( + realms=[ + RealmConfig(rp_id="a.com", auth_host="https://auth.a.com"), + RealmConfig( + rp_id="b.com", + origins=["https://auth.a.com"], + ), + ] + ) + ) + + def test_related_origin_inside_other_realm(self): + with pytest.raises(ValueError, match="falls inside realm"): + realms.validate_config( + Config( + realms=[ + RealmConfig(rp_id="a.com", origins=["https://app.b.com"]), + RealmConfig(rp_id="b.com"), + ] + ) + ) + + def test_auth_host_must_not_collide_with_rp_id(self): + with pytest.raises(ValueError, match="collides with an rp-id"): + realms.validate_config( + Config( + realms=[ + RealmConfig(rp_id="a.com", auth_host="https://b.a.com"), + RealmConfig(rp_id="b.a.com"), + ] + ) + ) + + +# ------------------------------------------------------------------------- +# ASGI dispatch +# ------------------------------------------------------------------------- + + +class TestDispatchMiddleware: + @pytest.mark.asyncio + async def test_http_unknown_host_421(self): + build_registry(*ROR_CONFIG.realms) + stub, sent = await drive_http( + DispatchMiddleware(StubApp()), [(b"host", b"evil.com")] + ) + assert stub.scope is None # Inner app not called + assert sent[0]["type"] == "http.response.start" + assert sent[0]["status"] == 421 + + @pytest.mark.asyncio + async def test_http_dispatches_realm(self): + build_registry(*ROR_CONFIG.realms) + stub, _sent = await drive_http( + DispatchMiddleware(StubApp()), [(b"host", b"app.com.")] + ) + assert stub.scope is not None + assert stub.scope["state"]["realm"].rp_id == "company.com" + + @pytest.mark.asyncio + async def test_http_current_realm_set_inside_request(self): + reg = build_registry(*ROR_CONFIG.realms) + seen = {} + + async def app(scope, receive, send): + seen["realm"] = realms.current_realm() + + await drive_http(DispatchMiddleware(app), [(b"host", b"pro.com")]) + assert seen["realm"].rp_id == "pro.com" + # Contextvar is reset after the request + assert realms.current_realm() is reg.default + + @pytest.mark.asyncio + async def test_ws_unknown_host_closed(self): + build_registry(*ROR_CONFIG.realms) + stub, sent = await drive_ws( + DispatchMiddleware(StubApp()), [(b"host", b"evil.com")] + ) + assert stub.scope is None + assert sent == [{"type": "websocket.close", "code": 1008}] + + @pytest.mark.asyncio + async def test_ws_same_realm_origin(self): + build_registry(*ROR_CONFIG.realms) + stub, sent = await drive_ws( + DispatchMiddleware(StubApp()), + [(b"host", b"auth.company.com"), (b"origin", b"https://app.com")], + ) + assert sent == [] + assert stub.scope["state"]["realm"].rp_id == "company.com" + + @pytest.mark.asyncio + async def test_ws_cross_realm_requires_effective_auth_host(self): + build_registry(*ROR_CONFIG.realms) + # pro.com page connecting to the shared auth host: allowed, pro realm + stub, sent = await drive_ws( + DispatchMiddleware(StubApp()), + [(b"host", b"auth.company.com"), (b"origin", b"https://pro.com")], + ) + assert sent == [] + assert stub.scope["state"]["realm"].rp_id == "pro.com" + + # pro.com page connecting to some other host: closed pre-accept + stub, sent = await drive_ws( + DispatchMiddleware(StubApp()), + [(b"host", b"company.com"), (b"origin", b"https://pro.com")], + ) + assert stub.scope is None + assert sent == [{"type": "websocket.close", "code": 1008}] + + @pytest.mark.asyncio + async def test_ws_unknown_origin_uses_host_realm(self): + build_registry(*ROR_CONFIG.realms) + # Missing origin + stub, _ = await drive_ws(DispatchMiddleware(StubApp()), [(b"host", b"pro.com")]) + assert stub.scope["state"]["realm"].rp_id == "pro.com" + # Unknown origin: host realm applies (endpoint-side validation decides) + stub, _ = await drive_ws( + DispatchMiddleware(StubApp()), + [(b"host", b"pro.com"), (b"origin", b"https://evil.com")], + ) + assert stub.scope["state"]["realm"].rp_id == "pro.com" + + +# ------------------------------------------------------------------------- +# Realm binding of auth codes +# ------------------------------------------------------------------------- + + +class TestAuthCodeRealmBinding: + @pytest.mark.asyncio + async def test_cookie_code_rejected_on_other_realm( + self, client: httpx.AsyncClient, session_token: str + ): + code = authcode.store_cookie( + authcode.CookieCode( + session_key=session_token, + created=datetime.now(UTC), + rp_id="other.com", + ) + ) + response = await client.post( + "/auth/api/set-session", + headers={ + "Authorization": f"Bearer {code}", + "Host": "localhost:4401", + }, + ) + assert response.status_code == 401 + + @pytest.mark.asyncio + async def test_oidc_code_rejected_on_other_realm( + self, client: httpx.AsyncClient, test_db: DB + ): + oidc_client, secret = Client.create( + name="Test Client", + redirect_uris=["https://client.example/callback"], + client_secret="topsecret", + ) + store = test_db._store + with store.transaction("create_test_oidc_client"): + test_db.oidc["localhost"].clients[oidc_client.uuid] = oidc_client + + code = authcode.store_oidc( + authcode.OIDCCode( + session_key="doesnotmatter1234", + created=datetime.now(UTC), + redirect_uri="https://client.example/callback", + scope="openid", + rp_id="other.com", + ) + ) + response = await client.post( + "/auth/oidc/token", + data={ + "grant_type": "authorization_code", + "code": code, + "redirect_uri": "https://client.example/callback", + "client_id": str(oidc_client.uuid), + "client_secret": secret, + }, + headers={"Host": "localhost:4401"}, + ) + assert response.status_code == 400 + assert response.json()["error"] == "invalid_grant" + assert "realm" in response.json()["error_description"] + + +# ------------------------------------------------------------------------- +# Legacy database conversion +# ------------------------------------------------------------------------- + + +def _read_db(path) -> DB: + async def _read() -> DB: + new_db = DB() + kanta = Kanta(str(path), new_db) + await kanta.open(readonly=True) + return kanta.data + + return asyncio.run(_read()) + + +class TestLegacyConversion: + def test_convert_stamps_realm_everywhere(self, tmp_path): + src = tmp_path / "example.com.paskiadb" + src.mkdir() + src_file = src / "main.db" + + cred_uuid = UUID("019c6831-84cf-7b88-b66c-c8165890b7c5") + user_uuid = UUID("019c6831-84cf-7b88-b66c-c8165890b7c6") + + async def _write() -> None: + kanta = Kanta(str(src_file), LegacyDB()) + await kanta.open() + with kanta.transaction("test:seed"): + kanta.data.config = LegacyConfig( + rp_id="example.com", + rp_name="Example", + origins=["https://app.example.com"], + ) + kanta.data.credentials[cred_uuid] = LegacyCredential( + credential_id=b"credential-id", + user_uuid=user_uuid, + aaguid=UUID(int=0), + public_key=b"public-key", + sign_count=3, + created_at=datetime.now(UTC), + ) + kanta.data.sessions["session-key"] = LegacySession( + user_uuid=user_uuid, + credential_uuid=cred_uuid, + host="example.com", + ip="127.0.0.1", + user_agent="pytest", + validated=datetime.now(UTC), + ) + await kanta.close() + + asyncio.run(_write()) + + config = convert_legacy_database(src_file, tmp_path / "paskia.kantadb") + assert config.default_realm.rp_id == "example.com" + assert config.default_realm.rp_name == "Example" + + converted = _read_db(tmp_path / "paskia.kantadb") + assert converted.credentials[cred_uuid].rp_id == "example.com" + assert converted.sessions["session-key"].rp_id == "example.com" + assert set(converted.oidc.keys()) == {"example.com"} + + +# ------------------------------------------------------------------------- +# Transaction log censoring +# ------------------------------------------------------------------------- + + +class TestLogCensoring: + def test_oidc_key_values_hidden(self): + assert format_log_uuid(b"raw-key-material", "oidc.localhost.key") == "" + assert format_log_uuid("secret", "oidc.example.com.key") == "" + + def test_oidc_key_path_component_visible(self): + # The path component itself must stay visible ("oidc..key = ") + assert format_log_uuid("key", "oidc.localhost.key") is None + + def test_other_paths_unaffected(self): + assert format_log_uuid("not-a-uuid", "oidc.localhost.clients") is None + assert format_log_uuid("not-a-uuid", "config.realms") is None + + +# ------------------------------------------------------------------------- +# Bootstrap caveat: admin credential is checked on the default realm +# ------------------------------------------------------------------------- + + +class TestBootstrapCaveat: + @pytest.mark.asyncio + async def test_admin_without_credentials_gets_link( + self, test_db: DB, realm_registry + ): + assert await check_admin_credentials() is True + + @pytest.mark.asyncio + async def test_admin_with_default_realm_credential_ok( + self, test_db: DB, realm_registry, test_user, test_credential + ): + assert await check_admin_credentials() is False + + @pytest.mark.asyncio + async def test_admin_with_only_other_realm_credential_gets_link( + self, test_db: DB, realm_registry, test_user + ): + """A passkey under a non-default realm does not satisfy the check.""" + cred = Credential.create( + credential_id=os.urandom(32), + user=test_user.uuid, + aaguid=UUID(int=0), + public_key=os.urandom(64), + sign_count=0, + rp_id="example.com", + ) + create_credential(cred) + assert await check_admin_credentials() is True -- 2.55.0 From 8e7acd6b9ec18a156f4637c398c420dda9c67541 Mon Sep 17 00:00:00 2001 From: Leo Vasanko Date: Sun, 6 Sep 2026 04:50:35 +0000 Subject: [PATCH 08/48] Frontend: realm admin UI, passkey realm badges, cross-realm notices MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Admin: replace Server Options dialog with per-realm management โ€” realms table on the overview, add/edit/delete realm dialog backed by /auth/api/admin/realms/. Origins may be any well-formed origin; non-subdomain ones are related origins (ROR, max 5) and the dialog points at the .well-known/webauthn URL that must list them. Connectivity checks compare against the edited realm's rp-id and degrade to warnings instead of blocking saves. - Host mode (limited profile) now keys off own_auth_host so realms sharing another realm's auth host serve the full profile locally. - Credential list shows a realm badge on passkeys registered for a different rp-id than the current realm. - Profile shows an enrollment prompt when the user has no passkey for the current realm (e.g. after a cross-realm remote login). - Remote auth permit shows the requesting realm when it differs from the approver's own. - settings cache can be force-refreshed after realm changes. --- frontend/auth/App.vue | 8 +- frontend/auth/admin/AdminApp.vue | 92 ++++++++---- frontend/src/admin/AdminDialogs.vue | 145 ++++++++++++------- frontend/src/admin/AdminOverview.vue | 56 ++++++- frontend/src/assets/style.css | 22 +++ frontend/src/components/CredentialList.vue | 6 + frontend/src/components/ProfileView.vue | 9 ++ frontend/src/components/RemoteAuthPermit.vue | 18 ++- frontend/src/stores/auth.js | 4 +- frontend/src/utils/settings.js | 3 +- 10 files changed, 274 insertions(+), 89 deletions(-) diff --git a/frontend/auth/App.vue b/frontend/auth/App.vue index 3933b54..73f50f0 100644 --- a/frontend/auth/App.vue +++ b/frontend/auth/App.vue @@ -37,11 +37,13 @@ function normalizeHost(raw) { } /** - * Host mode is active when an auth_host is configured AND the current host differs from it. + * Host mode is active when an own_auth_host is configured AND the current host differs from it. * In host mode, we show a limited profile view with logout and link to full profile. + * own_auth_host (not auth_host) is used so that realms sharing another realm's auth host + * still serve the full profile on their own hosts. */ const isHostMode = computed(() => { - const authHost = store.settings?.auth_host + const authHost = store.settings?.own_auth_host if (!authHost) return false const currentHost = normalizeHost(window.location.host) const configuredHost = normalizeHost(authHost) @@ -99,7 +101,7 @@ onMounted(async () => { if (rpName) { // In host mode, show "account summary" style title // Settings are loaded but isHostMode depends on them, so check here - const authHost = store.settings?.auth_host + const authHost = store.settings?.own_auth_host const inHostMode = authHost && normalizeHost(window.location.host) !== normalizeHost(authHost) document.title = inHostMode ? `${rpName} ยท Account summary` : rpName } diff --git a/frontend/auth/admin/AdminApp.vue b/frontend/auth/admin/AdminApp.vue index 8b1949a..f0fc8f0 100644 --- a/frontend/auth/admin/AdminApp.vue +++ b/frontend/auth/admin/AdminApp.vue @@ -28,6 +28,7 @@ const error = ref(null) const orgs = ref([]) const permissions = ref([]) const oidcClients = ref([]) +const realms = ref([]) const currentOrgId = ref(null) // UUID of selected org for detail view const currentUserId = ref(null) // UUID for user detail view const currentOidcId = ref(null) // UUID for OIDC client detail view @@ -174,6 +175,16 @@ async function loadAdminData() { oidcClients.value = Object.entries(data.oidc_clients).map(([uuid, c]) => ({ uuid, ...c })) } +// Realm list is master-admin only; callers guard on isMasterAdmin +async function loadRealms() { + try { + realms.value = await apiJson('/auth/api/admin/realms/') + } catch (e) { + console.warn('Unable to load realms', e) + realms.value = [] + } +} + // Helper to get users for a role as sorted array of [uuid, user] function roleUsers(org, roleUuid) { return Object.entries(org.users) @@ -207,6 +218,7 @@ function clearSensitiveState() { orgs.value = [] permissions.value = [] oidcClients.value = [] + realms.value = [] userDetail.value = null editingOidcClient.value = null authenticated.value = false @@ -236,6 +248,7 @@ async function load() { await loadAdminData() // If we get here, user has admin access - now fetch user info for display await loadUserInfo() + if (isMasterAdmin.value) await loadRealms() if (!isMasterAdmin.value && isOrgAdmin.value && orgs.value.length === 1) { if (!window.location.hash || window.location.hash === '#overview') { @@ -462,21 +475,41 @@ function createPermissionForClient(clientId) { openDialog('perm-create', { display_name: '', scope: '', domain: clientId }) } -async function openServerConfig() { - try { - const config = await apiJson('/auth/api/admin/server-config') - // Strip https:// scheme from stored origins and auth_host for editing - const origins = (config.origins || []).map(o => o.replace(/^https:\/\//, '')) - const auth_host = (config.auth_host || '').replace(/^https:\/\//, '') - openDialog('server-config', { - rp_name: config.rp_name || '', - auth_host, - origins, - originValidation: origins.map(() => null), - }) - } catch (e) { - authStore.showMessage(e.message || 'Failed to load server configuration', 'error') - } +function createRealm() { + openDialog('realm-edit', { + isNew: true, + rp_id: '', + rp_name: '', + auth_host: '', + origins: [], + originValidation: [], + authHostValidation: null, + }) +} + +function openRealm(realm) { + // Strip https:// scheme from stored origins and auth_host for editing + const origins = (realm.origins || []).map(o => o.replace(/^https:\/\//, '')) + openDialog('realm-edit', { + isNew: false, + rp_id: realm.rp_id, + rp_name: realm.rp_name || '', + auth_host: (realm.auth_host || '').replace(/^https:\/\//, ''), + origins, + originValidation: origins.map(() => null), + authHostValidation: null, + }) +} + +function deleteRealm(realm) { + openDialog('confirm', { + message: `Delete realm "${realm.rp_id}"? This is refused while any passkeys remain registered for it.`, + action: async () => { + await apiJson(`/auth/api/admin/realms/${realm.rp_id}`, { method: 'DELETE' }) + authStore.showMessage(`Realm "${realm.rp_id}" deleted.`, 'success', 2500) + await loadRealms() + } + }) } function deleteOidcClient(client) { @@ -900,25 +933,32 @@ async function submitDialog() { authStore.showMessage(e.message || `Failed to ${isNew ? 'create' : 'update'} OIDC client`, 'error') }) return // Don't call closeDialog() again - } else if (t === 'server-config') { - const rp_name = dialog.value.data.rp_name?.trim() || '' - const auth_host = dialog.value.data.auth_host?.trim() || '' + } else if (t === 'realm-edit') { + const d = dialog.value.data + const rp_id = d.rp_id?.trim().toLowerCase() + if (!rp_id) throw new Error('RP ID (domain) required') + const rp_name = d.rp_name?.trim() || '' + const auth_host = d.auth_host?.trim() || '' // Origins are stored as-is (hostnames); backend normalizes with https:// - const origins = dialog.value.data.origins + const origins = (d.origins || []) .map(o => o.trim()) .filter(o => o) closeDialog() - apiJson('/auth/api/admin/server-config', { method: 'PATCH', body: { rp_name, auth_host, origins } }) + const req = d.isNew + ? apiJson('/auth/api/admin/realms/', { method: 'POST', body: { rp_id, rp_name, auth_host, origins } }) + : apiJson(`/auth/api/admin/realms/${rp_id}`, { method: 'PATCH', body: { rp_name, auth_host, origins } }) + req .then(() => { - authStore.showMessage('Server configuration updated.', 'success', 2500) + authStore.showMessage(`Realm "${rp_id}" ${d.isNew ? 'created' : 'updated'}.`, 'success', 2500) + loadRealms() // Reload settings to reflect rp_name changes - authStore.loadSettings().then(() => { + authStore.loadSettings(true).then(() => { if (authStore.settings?.rp_name) document.title = authStore.settings.rp_name + ' Admin' }) }) .catch(e => { - authStore.showMessage(e.message || 'Failed to update server configuration', 'error') + authStore.showMessage(e.message || 'Failed to save realm', 'error') }) return // Don't call closeDialog() again } else if (t === 'confirm') { @@ -973,6 +1013,7 @@ async function submitDialog() { :orgs="orgs" :permissions="permissions" :oidc-clients="oidcClients" + :realms="realms" :navigation-disabled="hasActiveModal" :permission-summary="permissionSummary" @create-org="createOrg" @@ -986,7 +1027,9 @@ async function submitDialog() { @create-oidc-client="createOidcClient" @open-oidc-client="openOidcClient" @delete-oidc-client="deleteOidcClient" - @open-server-config="openServerConfig" + @create-realm="createRealm" + @open-realm="openRealm" + @delete-realm="deleteRealm" @navigate-out="handlePanelNavigateOut" /> @@ -1047,7 +1090,6 @@ async function submitDialog() { props.settings?.rp_id || 'the configured domain') const discoveryUrl = computed(() => `${window.location.origin}/.well-known/openid-configuration`) +// The rp-id of the realm being edited in the 'realm-edit' dialog +const realmRpId = computed(() => props.dialog?.data?.rp_id || '') + // Initialize validation properties -if (props.dialog?.data && props.dialog.type === 'server-config') { +if (props.dialog?.data && props.dialog.type === 'realm-edit') { if (!('authHostValidation' in props.dialog.data)) { props.dialog.data.authHostValidation = null } + if (!('originValidation' in props.dialog.data)) { + props.dialog.data.originValidation = (props.dialog.data.origins || []).map(() => null) + } } +// Block submit on hard errors: malformed entries, auth-host outside the +// rp-id domain, or validation still in flight. Connectivity and rp-id +// mismatch results are warnings only (e.g. related origins hosted elsewhere, +// or a new realm whose DNS is not routed to this instance yet). const isValidationInvalid = computed(() => { - if (props.dialog?.type !== 'server-config') return false + if (props.dialog?.type !== 'realm-edit') return false const d = props.dialog.data - if (d.authHostValidation?.startsWith('invalid') || d.authHostValidation === 'validating') return true + if (d.authHostValidation === 'invalid-domain' || d.authHostValidation === 'validating') return true if (d.originValidation?.some(v => v === 'invalid' || v === 'validating')) return true + if (props.dialog.type === 'realm-edit' && d.isNew && !isWellFormedDomain(d.rp_id || '')) return true return false }) +// Well-known URL that must list any related (non-subdomain) origins. +// Browsers always fetch it from the rp-id domain, never the auth host. +const wellKnownUrl = computed(() => { + const host = (props.dialog?.data?.rp_id || '').replace(/^https:\/\//, '').replace(/\/+$/, '') + return host ? `https://${host}/.well-known/webauthn` : '' +}) + +// Number of related (non-subdomain) origins in the realm dialog +const relatedOriginCount = computed(() => { + const d = props.dialog?.data + if (!d?.origins) return 0 + const id = realmRpId.value + return d.origins.filter(o => { + const h = originHostname(o) + return h && id && h !== id && !h.endsWith('.' + id) + }).length +}) + // Copy-to-clipboard helper const authStore = useAuthStore() function copyText(value, label) { @@ -43,7 +70,7 @@ function copyText(value, label) { function addOrigin() { const d = props.dialog?.data if (d) { - d.origins.push(rpId.value) + d.origins.push(realmRpId.value) d.originValidation.push(null) validateOrigin(d.origins[d.origins.length - 1], d.origins.length - 1) } @@ -67,17 +94,32 @@ function focusOriginStart(e) { e.target.setSelectionRange(0, 0) } -function validateOriginDomain(origin, rpId) { - if (!origin.trim()) return false +function isWellFormedDomain(value) { + if (!value.trim()) return false try { - const url = origin.startsWith('http') ? new URL(origin) : new URL('https://' + origin) - const hostname = url.hostname - return hostname === rpId || hostname.endsWith('.' + rpId) + const url = value.startsWith('http') ? new URL(value) : new URL('https://' + value) + return url.hostname.includes('.') || url.hostname === 'localhost' } catch { return false } } +function originHostname(origin) { + if (!origin.trim()) return null + try { + const url = origin.startsWith('http') ? new URL(origin) : new URL('https://' + origin) + return url.hostname || null + } catch { + return null + } +} + +function isWithinDomain(origin, rpId) { + const hostname = originHostname(origin) + if (!hostname) return false + return hostname === rpId || hostname.endsWith('.' + rpId) +} + async function validateOriginConnectivity(origin, i) { const d = props.dialog?.data if (!d) return @@ -90,22 +132,17 @@ async function validateOriginConnectivity(origin, i) { method: 'GET', headers: { 'Accept': 'application/json' } }) + if (d.origins[i] !== origin) return // origin changed while validating if (response.ok) { const data = await response.json() - // Check if it returns valid settings (has rp_id and matches current rp_id) - const result = (data.rp_id && data.rp_id === rpId.value) ? 'valid' : 'invalid' - // Only update if the origin hasn't changed - if (d.origins[i] === origin) { - d.originValidation[i] = result - } + // Valid when the origin is served by this instance for the edited realm + d.originValidation[i] = (data.rp_id && data.rp_id === realmRpId.value) ? 'valid' : 'mismatch' } else { - if (d.origins[i] === origin) { - d.originValidation[i] = 'invalid' - } + d.originValidation[i] = 'unreachable' } } catch (e) { if (d.origins[i] === origin) { - d.originValidation[i] = 'invalid' + d.originValidation[i] = 'unreachable' } } } @@ -114,8 +151,9 @@ function validateOrigin(origin, i) { const d = props.dialog?.data if (!d) return - const id = rpId.value - if (validateOriginDomain(origin, id)) { + // Related origins on unrelated domains are allowed (WebAuthn ROR), so any + // well-formed origin passes; connectivity is checked as a hint only. + if (originHostname(origin)) { validateOriginConnectivity(origin, i) } else { d.originValidation[i] = 'invalid' @@ -134,22 +172,16 @@ async function validateAuthHostConnectivity(authHost) { method: 'GET', headers: { 'Accept': 'application/json' } }) + if (d.auth_host !== authHost) return // auth_host changed while validating if (response.ok) { const data = await response.json() - // Check if it returns valid settings (has rp_id and matches current rp_id) - const result = (data.rp_id && data.rp_id === rpId.value) ? 'valid' : 'invalid' - // Only update if the auth_host hasn't changed - if (d.auth_host === authHost) { - d.authHostValidation = result - } + d.authHostValidation = (data.rp_id && data.rp_id === realmRpId.value) ? 'valid' : 'mismatch' } else { - if (d.auth_host === authHost) { - d.authHostValidation = 'invalid-connectivity' - } + d.authHostValidation = 'unreachable' } } catch (e) { if (d.auth_host === authHost) { - d.authHostValidation = 'invalid-connectivity' + d.authHostValidation = 'unreachable' } } } @@ -157,12 +189,11 @@ async function validateAuthHostConnectivity(authHost) { function validateAuthHost() { const d = props.dialog?.data if (!d || !d.auth_host?.trim()) { - d.authHostValidation = null // Allow empty + if (d) d.authHostValidation = null // Allow empty return } - const id = rpId.value - if (validateOriginDomain(d.auth_host, id)) { + if (isWithinDomain(d.auth_host, realmRpId.value)) { validateAuthHostConnectivity(d.auth_host) } else { d.authHostValidation = 'invalid-domain' @@ -181,7 +212,7 @@ function validateAuthHost() { - +