84 lines
3.3 KiB
Python
84 lines
3.3 KiB
Python
"""Minimal HTTPS client shared by application startup and the operator setup."""
|
|
|
|
from __future__ import annotations
|
|
|
|
import json
|
|
import os
|
|
import ssl
|
|
from pathlib import Path
|
|
from urllib.error import HTTPError, URLError
|
|
from urllib.request import HTTPRedirectHandler, HTTPSHandler, ProxyHandler, Request, build_opener
|
|
|
|
|
|
class BaoError(RuntimeError):
|
|
def __init__(self, path: str, status: int | None = None) -> None:
|
|
self.status = status
|
|
reason = f'HTTP {status}' if status else 'HTTPS connection failed'
|
|
super().__init__(f'OpenBao {path}: {reason}')
|
|
|
|
|
|
class NoRedirect(HTTPRedirectHandler):
|
|
def redirect_request(self, request, fp, code, msg, headers, newurl):
|
|
return None
|
|
|
|
|
|
class BaoClient:
|
|
def __init__(self, address: str, ca: str | Path,
|
|
identity: str | Path | None = None) -> None:
|
|
if not address.startswith('https://'):
|
|
raise ValueError('OpenBao address must be HTTPS')
|
|
self.address = address.rstrip('/')
|
|
context = ssl.create_default_context(cafile=str(ca))
|
|
if identity is not None:
|
|
identity = Path(identity)
|
|
context.load_cert_chain(identity / 'public.crt', identity / 'private.key')
|
|
self.opener = build_opener(ProxyHandler({}), HTTPSHandler(context=context), NoRedirect())
|
|
|
|
def request(self, path: str, data: dict | None = None, *,
|
|
method: str | None = None, token: str | None = None) -> dict:
|
|
headers = {'Content-Type': 'application/json'}
|
|
if token:
|
|
headers['X-Vault-Token'] = token
|
|
body = json.dumps(data).encode('utf-8') if data is not None else None
|
|
request = Request(f'{self.address}/v1/{path}', data=body, headers=headers, method=method)
|
|
try:
|
|
with self.opener.open(request, timeout=5) as response:
|
|
raw = response.read()
|
|
except HTTPError as error:
|
|
error.close()
|
|
raise BaoError(path, error.code) from None
|
|
except (URLError, OSError):
|
|
raise BaoError(path) from None
|
|
return json.loads(raw) if raw else {}
|
|
|
|
def login(self, role: str) -> dict:
|
|
return self.request('auth/cert/login', {'name': role})['auth']
|
|
|
|
def read_service(self, role: str, token: str) -> dict[str, str]:
|
|
return self.request(f'messenger/data/{role}', token=token)['data']['data']
|
|
|
|
|
|
_REQUIRED = {
|
|
'api': ('DATABASE_URL', 'REDIS_URL', 'S3_ACCESS_KEY_ID', 'S3_SECRET_ACCESS_KEY'),
|
|
'publisher': ('DATABASE_URL', 'BROKER_URL'),
|
|
'worker': ('DATABASE_URL', 'BROKER_URL', 'S3_ACCESS_KEY_ID', 'S3_SECRET_ACCESS_KEY'),
|
|
}
|
|
|
|
|
|
def load_workload_secrets() -> dict[str, str]:
|
|
role = os.environ['BAO_ROLE']
|
|
client = BaoClient(os.environ['BAO_ADDR'], os.environ['TLS_CA_FILE'], '/run/identity')
|
|
auth = client.login(role)
|
|
token = auth['client_token']
|
|
try:
|
|
bundle = client.read_service(role, token)
|
|
if not all(isinstance(bundle.get(key), str) and bundle[key] for key in _REQUIRED[role]):
|
|
raise RuntimeError(f'Incomplete OpenBao secret for role {role}')
|
|
return bundle
|
|
finally:
|
|
try:
|
|
client.request('auth/token/revoke-self', {}, token=token)
|
|
except BaoError:
|
|
# The token expires independently if the server became unavailable.
|
|
pass
|