forked from mtusi2026/mtusi2026lab7
88 lines
3.5 KiB
Python
88 lines
3.5 KiB
Python
"""Initialize/unseal the local OpenBao, then create per-service policies."""
|
|
|
|
import argparse
|
|
import json
|
|
import os
|
|
import ssl
|
|
import sys
|
|
import urllib.error
|
|
import urllib.request
|
|
from pathlib import Path
|
|
|
|
from pki import CA_CERT, PRIVATE
|
|
|
|
ROOT = Path(__file__).resolve().parents[1]
|
|
sys.path.insert(0, str(ROOT / "src"))
|
|
from bao_config import api_call # noqa: E402
|
|
|
|
BASE = "https://localhost:" + os.environ.get("BAO_PORT", "8200")
|
|
SECRETS = ROOT / "secrets"
|
|
STATE = SECRETS / "bao-operator.json"
|
|
FIELDS = {
|
|
"api": {"DATABASE_URL": "api_database_url", "CACHE_URL": "cache_url", "CURSOR_KEY": "cursor_key",
|
|
"S3_ACCESS_KEY": "s3_access", "S3_SECRET_KEY": "s3_secret"},
|
|
"worker": {"DATABASE_URL": "worker_database_url", "BROKER_URL": "worker_broker_url",
|
|
"S3_ACCESS_KEY": "worker_s3_access", "S3_SECRET_KEY": "worker_s3_secret"},
|
|
"relay": {"DATABASE_URL": "relay_database_url", "BROKER_URL": "relay_broker_url"},
|
|
}
|
|
|
|
|
|
def init(context):
|
|
if STATE.exists():
|
|
raise SystemExit("OpenBao operator material already exists. Use unseal.")
|
|
data = api_call(BASE, context, "sys/init", {"secret_shares": 3, "secret_threshold": 2})
|
|
descriptor = os.open(STATE, os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o600)
|
|
with os.fdopen(descriptor, "w", encoding="utf-8") as stream:
|
|
json.dump(data, stream)
|
|
print("Shares and root token saved for the local operator.")
|
|
|
|
|
|
def unseal(context, state):
|
|
for share in state["keys_base64"]:
|
|
result = api_call(BASE, context, "sys/unseal", {"key": share})
|
|
if not result["sealed"]:
|
|
return
|
|
raise SystemExit("OpenBao remains sealed.")
|
|
|
|
|
|
def install(context, state, selected):
|
|
token = state["root_token"]
|
|
if "messenger/" not in api_call(BASE, context, "sys/mounts", token=token):
|
|
api_call(BASE, context, "sys/mounts/messenger", {"type": "kv", "options": {"version": "2"}}, token)
|
|
if "cert/" not in api_call(BASE, context, "sys/auth", token=token):
|
|
api_call(BASE, context, "sys/auth/cert", {"type": "cert"}, token)
|
|
for role in selected:
|
|
policy = (ROOT / "infra" / "openbao" / f"{role}.hcl").read_text(encoding="utf-8")
|
|
api_call(BASE, context, f"sys/policies/acl/{role}", {"policy": policy}, token)
|
|
leaf = (PRIVATE / f"{role}-client.crt").read_text(encoding="ascii")
|
|
api_call(BASE, context, f"auth/cert/certs/{role}",
|
|
{"certificate": leaf, "allowed_dns_sans": [f"{role}-client"], "token_policies": [role],
|
|
"token_ttl": "90s", "token_max_ttl": "180s"}, token)
|
|
values = {key: (SECRETS / name).read_text(encoding="utf-8").strip()
|
|
for key, name in FIELDS[role].items()}
|
|
api_call(BASE, context, f"messenger/data/{role}", {"data": values}, token)
|
|
print("Service identities and KV configured.")
|
|
|
|
|
|
def main():
|
|
parser = argparse.ArgumentParser(description=__doc__)
|
|
parser.add_argument("action", choices=("init", "unseal", "install"))
|
|
parser.add_argument("--role", choices=FIELDS)
|
|
args = parser.parse_args()
|
|
context = ssl.create_default_context(cafile=CA_CERT)
|
|
try:
|
|
if args.action == "init":
|
|
init(context)
|
|
return
|
|
state = json.loads(STATE.read_text(encoding="utf-8"))
|
|
if args.action == "unseal":
|
|
unseal(context, state)
|
|
else:
|
|
install(context, state, (args.role,) if args.role else FIELDS)
|
|
except urllib.error.HTTPError as exc:
|
|
raise SystemExit(f"OpenBao returned HTTP {exc.code}. Check init, unseal and policy.") from None
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|