168 lines
6.0 KiB
Python
168 lines
6.0 KiB
Python
#!/usr/bin/env python3
|
|
"""Explicit operator actions. The host-only unseal shares are never mounted."""
|
|
import argparse
|
|
import json
|
|
import os
|
|
from pathlib import Path
|
|
import secrets
|
|
import subprocess
|
|
import time
|
|
from urllib.error import HTTPError
|
|
|
|
from scripts.local_pki import ROLES, ROOT, RUNTIME, write
|
|
from src.bao import client, request
|
|
|
|
ADDRESS = "https://localhost:8207"
|
|
MATERIAL = ROOT / "operator-raft"
|
|
SHARES = MATERIAL / "unseal.json"
|
|
INITIAL = MATERIAL / "initial-root"
|
|
IDENTITY = RUNTIME / "operator"
|
|
OPENER = client(*(str(IDENTITY / f) for f in ("service.crt", "service.key", "ca.crt")))
|
|
|
|
|
|
def call(path, body=None, token=None, method=None):
|
|
return request(OPENER, ADDRESS, path, body, token, method, timeout=25)
|
|
|
|
|
|
def unseal():
|
|
status = seal_status()
|
|
if status["sealed"]:
|
|
for share in json.loads(SHARES.read_text()):
|
|
status = call("sys/unseal", {"key": share}, method="PUT")
|
|
if not status["sealed"]:
|
|
break
|
|
if status["sealed"]:
|
|
raise RuntimeError("OpenBao is still sealed")
|
|
for _ in range(25):
|
|
try:
|
|
call("sys/health")
|
|
return
|
|
except OSError:
|
|
time.sleep(1)
|
|
raise RuntimeError("OpenBao did not become active after unseal")
|
|
|
|
|
|
def db_url(role, password):
|
|
return f"postgresql://lab_{role}:{password}@db:5432/messenger?sslmode=verify-full&sslrootcert=/pki/ca.crt"
|
|
|
|
|
|
def initial_values(role):
|
|
values = {"DATABASE_URL": db_url(role, (ROOT / "bootstrap" / "db" / role).read_text())}
|
|
if role != "dispatcher":
|
|
values["S3_ACCESS_KEY_ID"] = "lab-" + role
|
|
values["S3_SECRET_ACCESS_KEY"] = (ROOT / "bootstrap" / "s3" / role).read_text()
|
|
if role in {"dispatcher", "worker"}:
|
|
user = "producer" if role == "dispatcher" else "worker"
|
|
password = (ROOT / "bootstrap" / "broker" / user).read_text()
|
|
values["BROKER_URL"] = f"rediss://{user}:{password}@broker:6380/0"
|
|
return values
|
|
|
|
|
|
def login(role="operator"):
|
|
return call("auth/cert/login", {"name": role})["auth"]
|
|
|
|
|
|
def configure(token):
|
|
if "messenger/" not in call("sys/mounts", token=token):
|
|
call("sys/mounts/messenger", {"type": "kv", "options": {"version": "2"}}, token)
|
|
if "cert/" not in call("sys/auth", token=token):
|
|
call("sys/auth/cert", {"type": "cert"}, token)
|
|
ttl = int(os.getenv("BAO_TOKEN_TTL", "30"))
|
|
for role in (*ROLES, "operator"):
|
|
call("sys/policies/acl/" + role, {
|
|
"policy": (Path("infra/openbao") / (role + ".hcl")).read_text(),
|
|
}, token)
|
|
call("auth/cert/certs/" + role, {
|
|
"certificate": (RUNTIME / role / "service.crt").read_text(),
|
|
"allowed_dns_sans": [role],
|
|
"token_policies": [role],
|
|
"token_no_default_policy": True,
|
|
"token_ttl": "5m" if role == "operator" else f"{ttl}s",
|
|
"token_max_ttl": "5m" if role == "operator" else "5m",
|
|
"token_explicit_max_ttl": "5m",
|
|
}, token)
|
|
if role == "operator":
|
|
continue
|
|
try:
|
|
call("messenger/data/" + role, token=token)
|
|
except HTTPError as exc:
|
|
if exc.code != 404:
|
|
raise
|
|
call("messenger/data/" + role, {"data": initial_values(role)}, token)
|
|
|
|
|
|
def seal_status():
|
|
for _ in range(25):
|
|
try:
|
|
return call("sys/seal-status")
|
|
except OSError:
|
|
time.sleep(1)
|
|
raise RuntimeError("OpenBao HTTPS listener is unavailable")
|
|
|
|
|
|
def bootstrap():
|
|
MATERIAL.mkdir(mode=0o700, exist_ok=True)
|
|
status = seal_status()
|
|
if not status["initialized"]:
|
|
result = call("sys/init", {"secret_shares": 3, "secret_threshold": 2}, method="PUT")
|
|
write(SHARES, json.dumps(result["keys_base64"]), 0o600)
|
|
write(INITIAL, result["root_token"], 0o600)
|
|
unseal()
|
|
if INITIAL.exists():
|
|
token = INITIAL.read_text()
|
|
configure(token)
|
|
login()
|
|
call("auth/token/revoke-self", {}, token)
|
|
INITIAL.unlink()
|
|
else:
|
|
login()
|
|
|
|
|
|
def rotate_db():
|
|
token = login()["client_token"]
|
|
values = call("messenger/data/api", token=token)["data"]["data"]
|
|
password = secrets.token_hex(32)
|
|
# Send SQL over stdin. The local peer-auth socket belongs to the DB container.
|
|
subprocess.run(
|
|
["docker", "compose", "exec", "-T", "-u", "postgres", "db", "psql",
|
|
"-q", "-v", "ON_ERROR_STOP=1", "-d", "messenger"],
|
|
input=f"ALTER ROLE lab_api PASSWORD '{password}';\n",
|
|
text=True, check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
|
|
)
|
|
values["DATABASE_URL"] = db_url("api", password)
|
|
call("messenger/data/api", {"data": values}, token)
|
|
write(ROOT / "bootstrap" / "db" / "api", password)
|
|
# Close existing sessions to prove a subsequent connection cannot use the old credential.
|
|
subprocess.run(
|
|
["docker", "compose", "exec", "-T", "-u", "postgres", "db", "psql", "-q", "-d", "messenger"],
|
|
input="SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE usename='lab_api';\n",
|
|
text=True, check=True, stdout=subprocess.DEVNULL,
|
|
)
|
|
|
|
|
|
def rotate_s3():
|
|
token = login()["client_token"]
|
|
values = call("messenger/data/api", token=token)["data"]["data"]
|
|
password = secrets.token_hex(32)
|
|
path = ROOT / "bootstrap" / "s3" / "api"
|
|
write(path, password)
|
|
subprocess.run(["docker", "compose", "run", "--rm", "--no-deps", "-T", "-e", "S3_ROLE=api",
|
|
"s3-bootstrap"], stdin=subprocess.DEVNULL, check=True)
|
|
values["S3_SECRET_ACCESS_KEY"] = password
|
|
call("messenger/data/api", {"data": values}, token)
|
|
|
|
|
|
def main():
|
|
parser = argparse.ArgumentParser()
|
|
parser.add_argument("action", choices=("bootstrap", "unseal", "seal", "rotate-db", "rotate-s3"))
|
|
action = parser.parse_args().action
|
|
if action == "seal":
|
|
call("sys/seal", token=login()["client_token"], method="PUT")
|
|
else:
|
|
{"bootstrap": bootstrap, "unseal": unseal, "rotate-db": rotate_db, "rotate-s3": rotate_s3}[action]()
|
|
print("OpenBao operator action completed:", action)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|