Files
mtusi2026lab7/scripts/bootstrap-openbao-secrets.py

237 lines
5.7 KiB
Python

#!/usr/bin/env python3
"""Copy existing API/worker credentials to OpenBao KV v2."""
import hmac
import json
import os
import ssl
import stat
import subprocess
import sys
import urllib.error
import urllib.request
from pathlib import Path
BASE = Path.home() / ".local/share/mtusi2026lab7"
INIT_FILE = BASE / "operator/openbao-init.json"
CA_FILE = BASE / "pki/ca.crt"
BAO_URL = "https://localhost:8200"
SECRET_FIELDS = {
"api": (
"DATABASE_URL",
"S3_ACCESS_KEY",
"S3_SECRET_KEY",
),
"worker": (
"DATABASE_URL",
"RABBITMQ_USER",
"RABBITMQ_PASSWORD",
"S3_ACCESS_KEY",
"S3_SECRET_KEY",
),
}
def check(condition, message):
if not condition:
raise RuntimeError(message)
print("PASS:", message)
def request(method, path, token, context, payload=None):
data = None
if payload is not None:
data = json.dumps(payload).encode("utf-8")
headers = {"X-Vault-Token": token}
if data is not None:
headers["Content-Type"] = "application/json"
req = urllib.request.Request(
BAO_URL + path,
data=data,
headers=headers,
method=method,
)
try:
with urllib.request.urlopen(
req,
context=context,
timeout=15,
) as response:
body = response.read()
return (
response.status,
json.loads(body) if body else {},
)
except urllib.error.HTTPError as exc:
if exc.code == 404:
return 404, {}
# Do not print the response body or credentials.
raise RuntimeError(
"OpenBao request failed with HTTP {}".format(
exc.code
)
) from None
def equal_secrets(actual, expected):
if set(actual) != set(expected):
return False
return all(
isinstance(actual[key], str)
and hmac.compare_digest(actual[key], value)
for key, value in expected.items()
)
def main():
mode = stat.S_IMODE(INIT_FILE.stat().st_mode)
check(mode == 0o600, "Operator file permissions are 600")
with INIT_FILE.open(encoding="utf-8") as file:
root_token = json.load(file)["root_token"]
context = ssl.create_default_context(
cafile=str(CA_FILE)
)
result = subprocess.run(
["docker", "compose", "config", "--format", "json"],
check=True,
capture_output=True,
text=True,
)
services = json.loads(result.stdout)["services"]
api1_env = services["api1"]["environment"]
api2_env = services["api2"]["environment"]
worker_env = services["worker"]["environment"]
check(
all(
api1_env.get(key) == api2_env.get(key)
for key in SECRET_FIELDS["api"]
),
"API1 and API2 credentials match",
)
environments = {
"api": api1_env,
"worker": worker_env,
}
values = {}
for role, fields in SECRET_FIELDS.items():
source = environments[role]
values[role] = {
key: source.get(key)
for key in fields
}
check(
all(
isinstance(value, str) and bool(value)
for value in values[role].values()
),
"{} credentials are configured".format(role),
)
# Check existing KV values before making changes.
existing = {}
for role in SECRET_FIELDS:
path = "/v1/lab7/data/{}/runtime".format(role)
status, response = request(
"GET",
path,
root_token,
context,
)
if status == 404:
existing[role] = False
continue
stored = response["data"]["data"]
check(
equal_secrets(stored, values[role]),
"{} existing secret matches Compose".format(role),
)
existing[role] = True
# New secrets are created only when absent.
# CAS=0 prevents accidental overwriting.
for role in SECRET_FIELDS:
if existing[role]:
print("PASS: {} secret already stored".format(role))
continue
path = "/v1/lab7/data/{}/runtime".format(role)
status, _ = request(
"POST",
path,
root_token,
context,
{
"options": {"cas": 0},
"data": values[role],
},
)
check(
status in (200, 204),
"{} runtime secret stored".format(role),
)
# Read back and compare without displaying values.
for role in SECRET_FIELDS:
path = "/v1/lab7/data/{}/runtime".format(role)
status, response = request(
"GET",
path,
root_token,
context,
)
check(
status == 200
and equal_secrets(
response["data"]["data"],
values[role],
),
"{} KV v2 readback verified".format(role),
)
print("PASS: OpenBao HTTPS certificate verified")
print("PASS: API and worker secrets separated")
print("PASS: no credential values printed")
print("PASS: working application configuration unchanged")
if __name__ == "__main__":
try:
main()
except Exception as exc:
print(
"FAIL: secret bootstrap:",
type(exc).__name__,
file=sys.stderr,
)
raise SystemExit(1)