"""Клиент OpenBao AppRole; токены и тела ответов намеренно не попадают в журнал.""" import json import ssl from pathlib import Path import urllib.error import urllib.request from app.core.config import settings class SecretBootstrapError(RuntimeError): pass def _post(path: str, payload: dict, token: str | None = None) -> dict: body = json.dumps(payload).encode('utf-8') request = urllib.request.Request( settings.bao_addr.rstrip('/') + '/v1/' + path.lstrip('/'), data=body, headers={'Content-Type': 'application/json', **({'X-Vault-Token': token} if token else {})}, method='POST', ) context = ssl.create_default_context(cafile=settings.bao_cacert) try: with urllib.request.urlopen(request, context=context, timeout=4) as response: return json.loads(response.read()) except (OSError, urllib.error.URLError, ValueError): raise SecretBootstrapError('OpenBao authentication or secret read failed') from None def load_service_secrets() -> dict[str, str]: """Войти по AppRole текущего сервиса и прочитать только назначенный ему KV-путь.""" try: role_id = Path(settings.bao_role_id_file).read_text(encoding='utf-8').strip() secret_id = Path(settings.bao_secret_id_file).read_text(encoding='utf-8').strip() if not role_id or not secret_id: raise ValueError('empty AppRole credentials') except OSError: raise SecretBootstrapError('OpenBao AppRole files are unavailable') from None login = _post('auth/approle/login', {'role_id': role_id, 'secret_id': secret_id}) token = login.get('auth', {}).get('client_token') if not token: raise SecretBootstrapError('OpenBao AppRole login returned no token') try: request = urllib.request.Request( settings.bao_addr.rstrip('/') + '/v1/secret/data/' + settings.bao_secret_path.lstrip('/'), headers={'X-Vault-Token': token}, method='GET') context = ssl.create_default_context(cafile=settings.bao_cacert) with urllib.request.urlopen(request, context=context, timeout=4) as response: result = json.loads(response.read()) data = result['data']['data'] if not isinstance(data, dict) or not data: raise ValueError('empty KV data') return {str(key): str(value) for key, value in data.items()} except (OSError, urllib.error.URLError, ValueError, KeyError, TypeError): raise SecretBootstrapError('OpenBao scoped secret read failed') from None