""" backend/app/services/auth/sso/application_registry.py Purpose: Parse and validate peer services allowed to receive HXOPS SSO assertions. Dependencies: Flask configuration, JSON, URL parsing, and AppError. Flow: Assertion routes resolve app metadata here so browser-provided callback URLs are never trusted. """ from __future__ import annotations import json import re from dataclasses import dataclass from urllib.parse import urlparse from flask import current_app from app.core.errors import AppError, NotFoundError _APP_KEY_RE = re.compile(r'^[a-z0-9][a-z0-9_-]{1,63}$') @dataclass(frozen=True) class SsoApplication: """Registered peer-service metadata safe for server-controlled SSO routing.""" key: str display_name: str login_url: str callback_url: str audience: str enabled: bool = True def public_payload(self) -> dict[str, str]: """Return fields safe for authenticated HXOPS navigation components.""" return { 'key': self.key, 'display_name': self.display_name, 'login_url': self.login_url, } def _validate_http_url(value: str, *, field: str) -> str: """ Validate an application URL from server configuration. Args: value: Absolute browser or callback URL. field: Configuration field name used in diagnostics. Returns: Normalized URL without surrounding whitespace. Raises: AppError: URL is missing, malformed, or uses HTTP outside development/testing. """ normalized = str(value or '').strip() parsed = urlparse(normalized) if parsed.scheme not in {'http', 'https'} or not parsed.netloc: raise AppError( code='AUTH.SSO_CONFIG_ERROR', message=f'Invalid SSO application {field}', http_status=503, ) env_name = str(current_app.config.get('ENV_NAME') or current_app.config.get('FLASK_ENV') or '').lower() if parsed.scheme != 'https' and env_name not in {'dev', 'development', 'test', 'testing'}: raise AppError( code='AUTH.SSO_CONFIG_ERROR', message=f'SSO application {field} must use HTTPS', http_status=503, ) return normalized def list_applications() -> list[SsoApplication]: """ Parse the enabled SSO application registry from ``SSO_APPS_JSON``. Returns: Valid enabled application definitions. Raises: AppError: Configuration is invalid. Fail closed to avoid open redirects. """ if not bool(current_app.config.get('SSO_ENABLED', False)): return [] raw = current_app.config.get('SSO_APPS_JSON') or '[]' try: items = json.loads(raw) if isinstance(raw, str) else raw except (TypeError, ValueError) as exc: raise AppError( code='AUTH.SSO_CONFIG_ERROR', message='SSO application registry is invalid', http_status=503, ) from exc if not isinstance(items, list): raise AppError( code='AUTH.SSO_CONFIG_ERROR', message='SSO application registry must be a JSON array', http_status=503, ) applications: list[SsoApplication] = [] seen_keys: set[str] = set() seen_audiences: set[str] = set() for item in items: if not isinstance(item, dict) or not bool(item.get('enabled', True)): continue key = str(item.get('key') or '').strip().lower() audience = str(item.get('audience') or key).strip() display_name = str(item.get('display_name') or key).strip() if ( not _APP_KEY_RE.fullmatch(key) or not _APP_KEY_RE.fullmatch(audience.lower()) or audience != audience.lower() or not display_name ): raise AppError( code='AUTH.SSO_CONFIG_ERROR', message='SSO application identity configuration is incomplete', http_status=503, ) if key in seen_keys or audience in seen_audiences: raise AppError( code='AUTH.SSO_CONFIG_ERROR', message='SSO application keys and audiences must be unique', http_status=503, ) applications.append(SsoApplication( key=key, display_name=display_name, login_url=_validate_http_url(item.get('login_url'), field='login_url'), callback_url=_validate_http_url(item.get('callback_url'), field='callback_url'), audience=audience, enabled=True, )) seen_keys.add(key) seen_audiences.add(audience) return applications def get_application(app_key: str) -> SsoApplication: """Resolve one enabled application by its server-controlled key.""" normalized = str(app_key or '').strip().lower() for application in list_applications(): if application.key == normalized: return application raise NotFoundError('SSO application not found', code='AUTH.SSO_APP_NOT_FOUND')