Files
mtusi2026lab7-fork/scripts/bao_operator.py
T

56 lines
1.8 KiB
Python

#!/usr/bin/env python3
"""Initialize or unseal the local OpenBao; keep operator material on the host."""
import argparse
import json
import os
import ssl
from pathlib import Path
from urllib.error import HTTPError
from urllib.request import Request, urlopen
SECRETS = Path(__file__).resolve().parents[1] / "secrets"
MATERIAL = SECRETS / "bao-operator.json"
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("action", choices=("init", "unseal"))
action = parser.parse_args().action
context = ssl.create_default_context(cafile=str(SECRETS / "tls/lab7-ca.crt"))
def request(path, data):
req = Request(
"https://localhost:8200/v1/sys/" + path,
method="PUT",
data=json.dumps(data).encode(),
headers={"Content-Type": "application/json"},
)
with urlopen(req, context=context, timeout=15) as response:
return json.load(response)
if action == "init":
# Refuse to overwrite the operator's only copy of the material.
fd = os.open(MATERIAL, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
with os.fdopen(fd, "w") as output:
try:
data = request("init", {"secret_shares": 3, "secret_threshold": 2})
except HTTPError:
MATERIAL.unlink()
raise
json.dump(data, output)
output.flush()
os.fsync(output.fileno())
print("Operator material saved in secrets/bao-operator.json")
return
data = json.loads(MATERIAL.read_text())
for share in data["keys_base64"]:
if not request("unseal", {"key": share})["sealed"]:
print("OpenBao unsealed")
return
raise SystemExit("OpenBao remains sealed")
if __name__ == "__main__":
main()