67 lines
2.3 KiB
Python
67 lines
2.3 KiB
Python
"""Short-lived OpenBao certificate authentication; no root token or SecretID in app."""
|
|
|
|
import json
|
|
import os
|
|
import ssl
|
|
import threading
|
|
import time
|
|
import urllib.error
|
|
import urllib.request
|
|
|
|
from .domain import Failure
|
|
|
|
_lock = threading.Lock()
|
|
_values = {}
|
|
_valid_until = 0.0
|
|
_retry_after = 0.0
|
|
|
|
|
|
def request(path, *, data=None, token=None):
|
|
context = ssl.create_default_context(cafile=os.getenv("BAO_CA_FILE", "/run/tls/ca.pem"))
|
|
context.load_cert_chain("/run/tls/identity/cert.pem", "/run/tls/identity/key.pem")
|
|
headers = {"Content-Type": "application/json"}
|
|
if token:
|
|
headers["X-Vault-Token"] = token
|
|
payload = json.dumps(data).encode() if data is not None else None
|
|
req = urllib.request.Request(
|
|
os.environ["BAO_ADDR"] + "/v1/" + path, data=payload, headers=headers
|
|
)
|
|
with urllib.request.urlopen(req, context=context, timeout=2) as response:
|
|
return json.load(response)
|
|
|
|
|
|
def refresh():
|
|
global _values, _valid_until, _retry_after
|
|
if not os.getenv("BAO_ROLE"):
|
|
return
|
|
with _lock:
|
|
if time.monotonic() < _valid_until:
|
|
return
|
|
if time.monotonic() < _retry_after:
|
|
raise Failure(503, "Сервис секретов временно недоступен")
|
|
try:
|
|
role = os.environ["BAO_ROLE"]
|
|
auth = request("auth/cert/login", data={"name": role})["auth"]
|
|
values = request("secret/data/services/" + role, token=auth["client_token"])["data"][
|
|
"data"
|
|
]
|
|
# Never keep credentials usable beyond the auth token's short lease.
|
|
_values = values
|
|
_retry_after = 0.0
|
|
_valid_until = time.monotonic() + min(float(auth["lease_duration"]), 30) - 1
|
|
except (OSError, ValueError, TypeError, KeyError, urllib.error.URLError):
|
|
_values = {}
|
|
_valid_until = 0
|
|
# Bound concurrent failures: one network attempt, then a brief
|
|
# fail-closed negative cache instead of serial timeout storms.
|
|
_retry_after = time.monotonic() + 1
|
|
raise Failure(503, "Сервис секретов временно недоступен") from None
|
|
|
|
|
|
def value(name):
|
|
refresh()
|
|
try:
|
|
return _values[name]
|
|
except KeyError:
|
|
raise RuntimeError("Scoped secret unavailable: " + name) from None
|