Files
mtusi2026lab7/scripts/issue-openbao-bootstrap.py
T

151 lines
3.7 KiB
Python

#!/usr/bin/env python3
"""Issue a fresh one-time OpenBao AppRole bootstrap identity."""
import argparse
import json
import os
import ssl
import stat
import sys
import urllib.error
import urllib.request
from pathlib import Path
BASE = Path.home() / ".local/share/mtusi2026lab7"
OPERATOR = BASE / "operator"
INIT_FILE = OPERATOR / "openbao-init.json"
SERVICES = {
"api1": "messenger-api",
"api2": "messenger-api",
"worker": "messenger-worker",
}
def request(method, path, token, tls, payload=None):
body = None
if payload is not None:
body = json.dumps(payload).encode("utf-8")
headers = {"X-Vault-Token": token}
if body is not None:
headers["Content-Type"] = "application/json"
req = urllib.request.Request(
"https://localhost:8200/v1" + path,
data=body,
headers=headers,
method=method,
)
with urllib.request.urlopen(
req,
context=tls,
timeout=15,
) as response:
data = response.read()
return json.loads(data) if data else {}
def write_private(path, value):
fd = os.open(
path,
os.O_WRONLY | os.O_CREAT | os.O_EXCL,
0o600,
)
with os.fdopen(fd, "w", encoding="utf-8") as file:
file.write(value + "\n")
def main():
parser = argparse.ArgumentParser(
description="Issue one-time OpenBao bootstrap credentials"
)
parser.add_argument(
"service",
choices=sorted(SERVICES),
)
args = parser.parse_args()
if stat.S_IMODE(INIT_FILE.stat().st_mode) != 0o600:
raise RuntimeError("Operator file must have mode 600")
role = SERVICES[args.service]
destination = OPERATOR / "approle" / args.service
# Never overwrite credentials that may still be in use.
if destination.exists():
raise RuntimeError(
"Bootstrap directory already exists; refusing overwrite"
)
with INIT_FILE.open(encoding="utf-8") as file:
root_token = json.load(file)["root_token"]
tls = ssl.create_default_context(
cafile=str(BASE / "pki/ca.crt")
)
role_result = request(
"GET",
f"/auth/approle/role/{role}/role-id",
root_token,
tls,
)
role_id = role_result["data"]["role_id"]
secret_result = request(
"POST",
f"/auth/approle/role/{role}/secret-id",
root_token,
tls,
{},
)
secret_id = secret_result["data"]["secret_id"]
os.umask(0o077)
destination.mkdir(parents=True, mode=0o700)
try:
write_private(destination / "role-id", role_id)
write_private(destination / "secret-id", secret_id)
except Exception:
for name in ("role-id", "secret-id"):
(destination / name).unlink(missing_ok=True)
destination.rmdir()
raise
print(f"PASS: fresh bootstrap credentials issued for {args.service}")
print("PASS: separate AppRole identity used")
print("PASS: credentials stored outside Git")
print("PASS: credential files created with mode 600")
print("PASS: credential values not printed")
print("INFO: SecretID is valid for 30 minutes and one login")
if __name__ == "__main__":
try:
main()
except urllib.error.HTTPError as exc:
print(
f"FAIL: OpenBao returned HTTP {exc.code}",
file=sys.stderr,
)
raise SystemExit(1)
except Exception as exc:
print(
"FAIL: bootstrap issuance:",
type(exc).__name__,
file=sys.stderr,
)
raise SystemExit(1)