Files
mtusi2026lab7/scripts/bao_operator.py
T

184 lines
9.3 KiB
Python

#!/usr/bin/env python3
"""OpenBao operator actions of the lab 7 stand (docs/OPERATOR.md). Stdlib only; run on the host.
python scripts/bao_operator.py bootstrap # init (once) + unseal + configure + issue AppRole creds
python scripts/bao_operator.py unseal # after every OpenBao (re)start: it starts SEALED
python scripts/bao_operator.py status # initialized / sealed / mounts / roles (no secrets)
python scripts/bao_operator.py new-secret-id api # issue a new SecretID for one service
Who holds what:
* unseal shares (3, threshold 2) and the root token: the OPERATOR, in OPERATOR_DIR, outside the
repository (default ~/.mtusi-lab7-operator/<compose project>/, files 0600). Never in Git, never
in a container of the application, never printed. In a real team the 3 shares go to 3 people.
* role_id + secret_id of api / relay / worker: ./secrets/bao/ (git-ignored), each pair mounted as
a Docker secret ONLY into its own service - the "first secret" the service logs in with.
* the root token is used only by this script, for configuration.
Every secret travels to the OpenBao CLI over the STDIN of `docker compose exec` (never as a command
line argument or an environment variable of a process): the root token is the first stdin line,
read by `read -r BAO_TOKEN`; KV values and policies follow as JSON/HCL on stdin (`-`).
The CLI runs inside the openbao container against https://127.0.0.1:8200 with the internal CA
(BAO_ADDR/BAO_CACERT in compose.yaml): the server certificate is verified.
Idempotent: init only if not initialized; mounts/auth/policies/roles/KV are (re)written to the
state described here; an existing secret_id file is kept unless `new-secret-id` is asked.
"""
from __future__ import annotations
import json
import os
import subprocess
import sys
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
SECRETS = ROOT / "secrets"
POLICIES = ROOT / "infra" / "openbao" / "policies"
PROJECT = os.environ.get("COMPOSE_PROJECT_NAME", "mtusi-lab7")
OPERATOR_DIR = Path(os.environ.get("OPERATOR_DIR") or Path.home() / ".mtusi-lab7-operator" / PROJECT)
SHARES, THRESHOLD = 3, 2
# Token of a service: 1 h, at most 4 h with renewals; the services revoke it right after reading.
# SecretID: valid 30 days, unlimited logins (every restart of a replica logs in again).
ROLE_SETTINGS = ["token_ttl=1h", "token_max_ttl=4h", "token_type=service", "token_no_default_policy=true",
"secret_id_ttl=720h", "secret_id_num_uses=0"]
# What each service may read: KV v2 messenger/data/<service>. Values come from ./secrets.
SERVICE_SECRETS = {
"api": {"database_url": "database_url_api", "cache_url": "cache_url",
"s3_access_key_id": "s3_api_access_key_id", "s3_secret_access_key": "s3_api_secret_access_key"},
"relay": {"database_url": "database_url_relay", "broker_url": "broker_url_relay"},
"worker": {"database_url": "database_url_worker", "broker_url": "broker_url_worker",
"s3_access_key_id": "s3_worker_access_key_id", "s3_secret_access_key": "s3_worker_secret_access_key"},
}
def say(text: str) -> None:
print(f"bao-operator: {text}", flush=True)
def bao(*args: str, token: str | None = None, stdin: bytes = b"", check: bool = True) -> subprocess.CompletedProcess:
"""Run `bao <args>` inside the openbao container; the token (if any) is the first stdin line."""
script = 'read -r BAO_TOKEN; export BAO_TOKEN; exec bao "$@"' if token else 'exec bao "$@"'
data = ((token + "\n").encode() if token else b"") + stdin
result = subprocess.run(["docker", "compose", "exec", "-T", "openbao", "sh", "-c", script, "sh", *args],
input=data, capture_output=True, cwd=ROOT)
if check and result.returncode != 0:
# stderr of the CLI names the failing path/permission; it never contains our stdin data.
raise SystemExit(f"bao-operator: `bao {' '.join(args)}` failed: {result.stderr.decode(errors='replace').strip()[:400]}")
return result
def status() -> dict:
result = bao("status", "-format=json", check=False) # exit 2 = sealed, still prints JSON
if result.returncode not in (0, 2):
raise SystemExit("bao-operator: OpenBao is not reachable (is `docker compose up -d openbao` running?): "
+ result.stderr.decode(errors="replace").strip()[:300])
return json.loads(result.stdout)
def private_write(path: Path, value: str) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(value + "\n", encoding="utf-8", newline="\n")
os.chmod(path, 0o600)
def operator_file(name: str) -> str:
path = OPERATOR_DIR / name
if not path.exists():
raise SystemExit(f"bao-operator: {path} is missing: the operator material of this OpenBao is not here")
return path.read_text(encoding="utf-8").strip()
def init() -> None:
if status()["initialized"]:
say("already initialized")
return
if (OPERATOR_DIR / "root-token").exists():
raise SystemExit(f"bao-operator: OpenBao is NOT initialized but {OPERATOR_DIR} has material of an older "
"instance; move it away first (it does not belong to this storage)")
out = json.loads(bao("operator", "init", f"-key-shares={SHARES}", f"-key-threshold={THRESHOLD}", "-format=json").stdout)
for i, share in enumerate(out["unseal_keys_b64"], 1):
private_write(OPERATOR_DIR / f"unseal-share-{i}", share)
private_write(OPERATOR_DIR / "root-token", out["root_token"])
os.chmod(OPERATOR_DIR, 0o700)
say(f"initialized: {SHARES} unseal shares (threshold {THRESHOLD}) and the root token saved to {OPERATOR_DIR} "
"(outside the repository; not printed)")
def unseal() -> None:
state = status()
if not state["initialized"]:
raise SystemExit("bao-operator: not initialized yet: run `bootstrap`")
if not state["sealed"]:
say("already unsealed")
return
for i in range(1, THRESHOLD + 1):
bao("write", "-format=json", "sys/unseal", "key=-", stdin=operator_file(f"unseal-share-{i}").encode())
state = status()
if state["sealed"]:
raise SystemExit("bao-operator: still sealed after the threshold of shares")
say(f"unsealed with {THRESHOLD} of {SHARES} shares")
def secret(name: str) -> str:
return (SECRETS / name).read_text(encoding="utf-8").strip()
def configure() -> None:
token = operator_file("root-token")
mounts = json.loads(bao("secrets", "list", "-format=json", token=token).stdout)
if "messenger/" not in mounts:
bao("secrets", "enable", "-path=messenger", "-version=2", "kv", token=token)
say("KV v2 mounted at messenger/")
auths = json.loads(bao("auth", "list", "-format=json", token=token).stdout)
if "approle/" not in auths:
bao("auth", "enable", "approle", token=token)
say("auth method approle enabled")
# The audit device (file -> container stdout) is declared in infra/openbao/config.hcl:
# OpenBao 2.7 refuses to enable audit devices over the API.
for service, values in SERVICE_SECRETS.items():
bao("policy", "write", service, "-", token=token, stdin=(POLICIES / f"{service}.hcl").read_bytes())
bao("write", f"auth/approle/role/{service}", f"token_policies={service}", *ROLE_SETTINGS, token=token)
data = {key: secret(source) for key, source in values.items()}
bao("kv", "put", "-mount=messenger", service, "-", token=token, stdin=json.dumps(data).encode())
role_id = json.loads(bao("read", "-format=json", f"auth/approle/role/{service}/role-id", token=token).stdout)["data"]["role_id"]
private_write(SECRETS / "bao" / f"{service}_role_id", role_id)
os.chmod(SECRETS / "bao" / f"{service}_role_id", 0o644) # readable by the container user (bind mount)
if not (SECRETS / "bao" / f"{service}_secret_id").exists():
issue_secret_id(service, token)
say(f"{service}: policy {service} (read messenger/data/{service}), AppRole, KV keys {sorted(data)}")
def issue_secret_id(service: str, token: str | None = None) -> None:
token = token or operator_file("root-token")
out = json.loads(bao("write", "-f", "-format=json", f"auth/approle/role/{service}/secret-id", token=token).stdout)
path = SECRETS / "bao" / f"{service}_secret_id"
private_write(path, out["data"]["secret_id"])
os.chmod(path, 0o644) # the service reads it through the bind mount (folder ./secrets is 0700)
say(f"{service}: new SecretID written to secrets/bao/{service}_secret_id (TTL 720h; not printed)")
def main(argv: list[str]) -> int:
command = argv[0] if argv else "status"
if command == "bootstrap":
init()
unseal()
configure()
say("done; start the stand: docker compose up -d --build --wait")
elif command == "unseal":
unseal()
elif command == "status":
state = status()
say(f"initialized={state['initialized']} sealed={state['sealed']} storage={state.get('storage_type')} "
f"version={state.get('version')} operator_dir={OPERATOR_DIR}")
elif command == "new-secret-id" and len(argv) == 2 and argv[1] in SERVICE_SECRETS:
issue_secret_id(argv[1])
say(f"restart the service to use it: docker compose up -d --force-recreate {argv[1]}")
else:
print(__doc__)
return 2
return 0
if __name__ == "__main__":
sys.exit(main(sys.argv[1:]))