"""Verified local HTTPS transport shared by preserved lab1–6 operator tools.""" from __future__ import annotations import json import os from pathlib import Path import ssl import urllib.parse import urllib.request from lab7_environment import ROOT, read_env _SETTINGS = read_env(ROOT / '.env') def _value(name: str, fallback: str) -> str: return os.environ.get(name, _SETTINGS.get(name, fallback)) def _path(value: str) -> Path: path = Path(value).expanduser() return path if path.is_absolute() else ROOT / path SECRETS_DIR = _path(_value('LAB7_SECRETS_DIR', 'secrets/lab7')) OPERATOR_IDENTITY = SECRETS_DIR / 'pki/operator/current' CA_FILE = str(_path(_value('CA_FILE', str(OPERATOR_IDENTITY / 'ca.crt')))) BASE_URL = _value('BASE_URL', 'https://localhost:' + _value('PUBLIC_PORT', '8443')) class _HTTPSOnly(urllib.request.HTTPHandler): def http_open(self, request): raise ValueError('legacy operator tools require a verified HTTPS URL') class _NoRedirect(urllib.request.HTTPRedirectHandler): def redirect_request(self, request, response, code, message, headers, new_url): return None def public_context(ca_file: str | None = CA_FILE) -> ssl.SSLContext: context = ssl.create_default_context(cafile=str(_path(ca_file or CA_FILE))) context.minimum_version = ssl.TLSVersion.TLSv1_2 return context def public_opener(ca_file: str | None = CA_FILE) -> urllib.request.OpenerDirector: return urllib.request.build_opener( urllib.request.ProxyHandler({}), _HTTPSOnly(), _NoRedirect(), urllib.request.HTTPSHandler(context=public_context(ca_file)), ) def operator_opener(ca_file: str | None = CA_FILE) -> urllib.request.OpenerDirector: # Resolve the immutable identity snapshot once so rotation cannot mix key/cert. identity = OPERATOR_IDENTITY.resolve(strict=True) ca_path = _path(ca_file or CA_FILE) if ca_path == OPERATOR_IDENTITY / 'ca.crt': ca_path = identity / 'ca.crt' context = public_context(str(ca_path)) context.load_cert_chain( str(_path(_value('OPERATOR_CERT_FILE', str(identity / 'tls.crt')))), str(_path(_value('OPERATOR_KEY_FILE', str(identity / 'tls.key')))), ) return urllib.request.build_opener( urllib.request.ProxyHandler({}), _HTTPSOnly(), _NoRedirect(), urllib.request.HTTPSHandler(context=context), ) def open_url(url_or_request, timeout: float = 10, *, operator: bool = False, ca_file: str | None = CA_FILE): url = url_or_request.full_url if isinstance(url_or_request, urllib.request.Request) else url_or_request if urllib.parse.urlsplit(url).scheme != 'https': raise ValueError('legacy operator tools require a verified HTTPS URL') opener = operator_opener(ca_file) if operator else public_opener(ca_file) return opener.open(url_or_request, timeout=timeout) def grafana_password() -> str: credentials = json.loads((SECRETS_DIR / 'backends/credentials.json').read_text()) password = credentials['grafana']['password'] if not isinstance(password, str) or not password: raise ValueError('operator Grafana password is missing') return password