33 lines
1.2 KiB
Python
33 lines
1.2 KiB
Python
"""Small JSON client for the authenticated OpenBao HTTPS API."""
|
|
import json
|
|
import urllib.request
|
|
from urllib.error import HTTPError
|
|
|
|
|
|
class Bao:
|
|
def __init__(self, base, context, timeout=3):
|
|
self.base = base
|
|
self.context = context
|
|
self.timeout = timeout
|
|
|
|
def request(self, path, body=None, token=None, method=None):
|
|
data = json.dumps(body).encode() if body is not None else None
|
|
headers = {"Content-Type": "application/json"}
|
|
if token:
|
|
headers["X-Vault-Token"] = token
|
|
request = urllib.request.Request(self.base + "/v1/" + path, data=data,
|
|
headers=headers, method=method)
|
|
try:
|
|
with urllib.request.urlopen(request, context=self.context, timeout=self.timeout) as response:
|
|
return json.load(response) if response.status != 204 else {}
|
|
except HTTPError as exc:
|
|
# Error bodies can include private material. Status alone is enough for callers.
|
|
exc.close()
|
|
raise BaoError(exc.code) from None
|
|
|
|
|
|
class BaoError(Exception):
|
|
def __init__(self, status):
|
|
self.status = status
|
|
super().__init__(f"OpenBao HTTP {status}")
|