Files
mtusi2026lab7/scripts/configure-openbao-cert-auth.py
T

125 lines
3.1 KiB
Python

#!/usr/bin/env python3
"""Configure scoped certificate authentication in OpenBao."""
import json
import ssl
import sys
import urllib.error
import urllib.request
from pathlib import Path
BASE = Path.home() / ".local/share/mtusi2026lab7"
URL = "https://localhost:8200/v1"
SERVICES = {
"api1": "messenger-api",
"api2": "messenger-api",
"worker": "messenger-worker",
}
def request(method, path, token, tls, payload=None):
headers = {"X-Vault-Token": token}
body = None
if payload is not None:
body = json.dumps(payload).encode("utf-8")
headers["Content-Type"] = "application/json"
req = urllib.request.Request(
URL + path,
data=body,
headers=headers,
method=method,
)
with urllib.request.urlopen(
req,
context=tls,
timeout=15,
) as response:
raw = response.read()
return json.loads(raw) if raw else {}
def main():
with (BASE / "operator/openbao-init.json").open(
encoding="utf-8"
) as file:
root_token = json.load(file)["root_token"]
tls = ssl.create_default_context(
cafile=str(BASE / "pki/ca.crt")
)
methods = request(
"GET",
"/sys/auth",
root_token,
tls,
)
if "cert/" not in methods:
request(
"POST",
"/sys/auth/cert",
root_token,
tls,
{"type": "cert"},
)
print("PASS: certificate auth method enabled")
elif methods["cert/"]["type"] == "cert":
print("PASS: certificate auth method already enabled")
else:
raise RuntimeError("Unexpected auth method at cert/")
for service, policy in SERVICES.items():
certificate = (
BASE
/ "pki/openbao-clients"
/ f"{service}.crt"
).read_text(encoding="ascii")
request(
"POST",
f"/auth/cert/certs/lab7-{service}",
root_token,
tls,
{
"certificate": certificate,
"display_name": f"lab7-{service}",
"token_policies": [policy],
"token_no_default_policy": True,
"token_ttl": "1200s",
"token_max_ttl": "3600s",
"token_type": "service",
"token_num_uses": 0,
},
)
print(
f"PASS: {service} certificate registered "
f"with {policy} policy"
)
print("PASS: three scoped certificate identities configured")
print("PASS: no private keys or tokens printed")
if __name__ == "__main__":
try:
main()
except urllib.error.HTTPError as exc:
print(
f"FAIL: OpenBao HTTP {exc.code}",
file=sys.stderr,
)
raise SystemExit(1)
except Exception as exc:
print(
"FAIL: certificate auth configuration:",
type(exc).__name__,
file=sys.stderr,
)
raise SystemExit(1)