211 lines
9.0 KiB
Python
Executable File
211 lines
9.0 KiB
Python
Executable File
#!/usr/bin/env python3
|
|
"""Bootstrap and operate the isolated, synthetic lab deployment."""
|
|
import argparse
|
|
import json
|
|
import os
|
|
from pathlib import Path
|
|
import secrets
|
|
import ssl
|
|
import subprocess
|
|
import sys
|
|
import time
|
|
|
|
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
|
|
from bao_client import Bao, BaoError
|
|
from scripts.pki import OPERATOR, ROOT, RUN, SECRETS, init, write
|
|
|
|
INIT_STATE = OPERATOR / "bao-init.json"
|
|
SEED = OPERATOR / "seed.json"
|
|
|
|
|
|
def compose(*arguments, **kwargs):
|
|
return subprocess.run(["docker", "compose", *arguments], cwd=ROOT, check=True, **kwargs)
|
|
|
|
|
|
def settings():
|
|
path = ROOT / ".env"
|
|
return dict(line.split("=", 1) for line in path.read_text().splitlines()
|
|
if line and not line.startswith("#") and "=" in line) if path.exists() else {}
|
|
|
|
|
|
def administrative_bao():
|
|
cert = str(SECRETS / "trust" / "openbao.crt")
|
|
context = ssl.create_default_context(cafile=cert)
|
|
return Bao("https://127.0.0.1:" + settings().get("BAO_PORT", "8277"), context, timeout=30)
|
|
|
|
|
|
def prepare():
|
|
init()
|
|
if not SEED.exists():
|
|
values = {key: secrets.token_hex(24) for key in ("postgres", "bao_db", "cursor", "grafana")}
|
|
for role in ("api", "worker", "root"):
|
|
values[role + "_user"] = role + "-" + secrets.token_hex(8)
|
|
values[role + "_secret"] = secrets.token_hex(24)
|
|
write(SEED, json.dumps(values).encode(), 0o600)
|
|
values = json.loads(SEED.read_text())
|
|
write(RUN / "postgres" / "postgres_password", values["postgres"].encode())
|
|
postgres_url = (f"postgresql://owner:{values['postgres']}@postgres:5432/messenger"
|
|
"?sslmode=verify-full&sslrootcert=/run/operator/ca.crt&connect_timeout=3")
|
|
write(RUN / "migrate" / "database_url", postgres_url.encode())
|
|
write(RUN / "migrate" / "ca.crt", (RUN / "postgres" / "ca.crt").read_bytes())
|
|
write(RUN / "grafana-config" / "grafana_password", values["grafana"].encode())
|
|
root_s3 = (f"export RUSTFS_ACCESS_KEY={values['root_user']}\n"
|
|
f"export RUSTFS_SECRET_KEY={values['root_secret']}\n")
|
|
write(RUN / "s3-store" / "env", root_s3.encode())
|
|
s3 = root_s3 + "".join(f"{r.upper()}_S3_USER={values[r + '_user']}\n"
|
|
f"{r.upper()}_S3_PASSWORD={values[r + '_secret']}\n" for r in ("api", "worker"))
|
|
write(RUN / "s3-bootstrap" / "env", s3.encode())
|
|
write(RUN / "s3-bootstrap" / "ca.crt", (RUN / "rustfs" / "ca.crt").read_bytes())
|
|
|
|
|
|
def wait_for_bao(bao):
|
|
for _ in range(30):
|
|
try:
|
|
return bao.request("sys/seal-status")
|
|
except OSError:
|
|
time.sleep(1)
|
|
raise SystemExit("OpenBao HTTPS listener unavailable")
|
|
|
|
|
|
def initialize_bao(bao):
|
|
state = wait_for_bao(bao)
|
|
if state["initialized"]:
|
|
if not INIT_STATE.exists():
|
|
raise SystemExit("The operator's existing init state must be supplied")
|
|
return
|
|
if INIT_STATE.exists():
|
|
raise SystemExit("Existing init material belongs to another storage volume")
|
|
config = bao.request("sys/init", {"secret_shares": 3, "secret_threshold": 2}, method="PUT")
|
|
write(INIT_STATE, json.dumps(config).encode(), 0o600)
|
|
print("Initialized persistent OpenBao. Operator material saved locally with mode 0600.")
|
|
|
|
|
|
def operator_credentials():
|
|
return json.loads(INIT_STATE.read_text())
|
|
|
|
|
|
def unseal(bao):
|
|
state = wait_for_bao(bao)
|
|
if not state["sealed"]:
|
|
return
|
|
for share in operator_credentials()["keys_base64"][:2]:
|
|
state = bao.request("sys/unseal", {"key": share}, method="PUT")
|
|
if state["sealed"]:
|
|
raise SystemExit("OpenBao remains sealed")
|
|
print("OpenBao unsealed by operator.")
|
|
|
|
|
|
def provision_database():
|
|
config = json.loads(SEED.read_text())
|
|
sql = rf"""
|
|
SELECT 'CREATE ROLE messenger_api NOLOGIN' WHERE NOT EXISTS (SELECT FROM pg_roles WHERE rolname='messenger_api') \gexec
|
|
SELECT 'CREATE ROLE messenger_worker NOLOGIN' WHERE NOT EXISTS (SELECT FROM pg_roles WHERE rolname='messenger_worker') \gexec
|
|
SELECT 'CREATE ROLE bao_db LOGIN CREATEROLE' WHERE NOT EXISTS (SELECT FROM pg_roles WHERE rolname='bao_db') \gexec
|
|
ALTER ROLE bao_db PASSWORD '{config['bao_db']}';
|
|
GRANT messenger_api, messenger_worker TO bao_db WITH ADMIN OPTION;
|
|
"""
|
|
compose("exec", "-T", "postgres", "psql", "-X", "-U", "owner", "-d", "messenger",
|
|
"--set=ON_ERROR_STOP=1", input=sql.encode(), stdout=subprocess.DEVNULL)
|
|
|
|
|
|
def configure_bao(bao):
|
|
token = operator_credentials()["root_token"]
|
|
values = json.loads(SEED.read_text())
|
|
auth = bao.request("sys/auth", token=token)
|
|
mounts = bao.request("sys/mounts", token=token)
|
|
if "cert/" not in auth:
|
|
bao.request("sys/auth/cert", {"type": "cert"}, token)
|
|
for path, body in (("runtime", {"type": "kv", "options": {"version": "2"}}),
|
|
("database", {"type": "database"})):
|
|
if path + "/" not in mounts:
|
|
bao.request("sys/mounts/" + path, body, token)
|
|
ca = (RUN / "openbao" / "ca.crt").read_text()
|
|
bao.request("database/config/messenger", {
|
|
"plugin_name": "postgresql-database-plugin",
|
|
"connection_url": ("postgresql://{{username}}:{{password}}@postgres:5432/messenger"
|
|
"?sslmode=verify-full&sslrootcert=/run/identity/ca.crt"),
|
|
"username": "bao_db", "password": values["bao_db"],
|
|
"allowed_roles": ["api", "worker"], "max_open_connections": 3,
|
|
}, token)
|
|
policy = (ROOT / "infra/openbao/service-policy.hcl").read_text()
|
|
for role in ("api", "worker"):
|
|
bao.request("sys/policies/acl/" + role, {"policy": policy.replace("ROLE", role)}, token)
|
|
bao.request("auth/cert/certs/" + role, {
|
|
"certificate": ca, "allowed_common_names": [role],
|
|
"allowed_uri_sans": ["spiffe://lab7/" + role],
|
|
"token_policies": [role], "token_no_default_policy": True,
|
|
"token_ttl": "45s", "token_max_ttl": "150s",
|
|
}, token)
|
|
bao.request("database/roles/" + role, {
|
|
"db_name": "messenger", "default_ttl": "40s", "max_ttl": "120s",
|
|
"creation_statements": [f"""CREATE ROLE "{{{{name}}}}" WITH LOGIN PASSWORD '{{{{password}}}}'
|
|
VALID UNTIL '{{{{expiration}}}}' IN ROLE messenger_{role};"""],
|
|
"renew_statements": ["""ALTER ROLE "{{name}}" VALID UNTIL '{{expiration}}';"""],
|
|
"revocation_statements": ['DROP ROLE IF EXISTS "{{name}}";'],
|
|
}, token)
|
|
try:
|
|
bao.request("runtime/data/" + role, token=token)
|
|
except BaoError as exc:
|
|
if exc.status != 404:
|
|
raise
|
|
data = {"S3_ACCESS_KEY_ID": values[role + "_user"],
|
|
"S3_SECRET_ACCESS_KEY": values[role + "_secret"]}
|
|
if role == "api":
|
|
data["CURSOR_SECRET"] = values["cursor"]
|
|
bao.request("runtime/data/" + role, {"data": data}, token)
|
|
print("Enabled audit, certificate auth, separate policies and short database leases.")
|
|
|
|
|
|
def rotate_s3(bao, stage, username=None):
|
|
token = operator_credentials()["root_token"]
|
|
path = "runtime/data/worker"
|
|
current = bao.request(path, token=token)["data"]
|
|
if stage == "add":
|
|
data = {"S3_ACCESS_KEY_ID": "worker-" + secrets.token_hex(8),
|
|
"S3_SECRET_ACCESS_KEY": secrets.token_hex(24)}
|
|
payload = "\n".join(data.values()) + "\n"
|
|
compose("run", "--rm", "--no-deps", "-T", "bucket-bootstrap", "add",
|
|
input=payload.encode(), stdout=sys.stderr)
|
|
bao.request(path, {"options": {"cas": current["metadata"]["version"]}, "data": data}, token)
|
|
seed = json.loads(SEED.read_text())
|
|
seed.update(worker_user=data["S3_ACCESS_KEY_ID"], worker_secret=data["S3_SECRET_ACCESS_KEY"])
|
|
write(SEED, json.dumps(seed).encode(), 0o600)
|
|
print(current["data"]["S3_ACCESS_KEY_ID"])
|
|
else:
|
|
if not username or username == current["data"]["S3_ACCESS_KEY_ID"]:
|
|
raise SystemExit("Supply only the previous identity after checking the new worker")
|
|
compose("run", "--rm", "--no-deps", "-T", "bucket-bootstrap", "remove",
|
|
input=(username + "\n").encode())
|
|
print("Previous S3 identity revoked.")
|
|
|
|
|
|
def main():
|
|
parser = argparse.ArgumentParser(description=__doc__)
|
|
parser.add_argument("action", choices=("prepare", "init", "unseal", "seal", "configure",
|
|
"rotate-s3-add", "rotate-s3-remove", "database"))
|
|
parser.add_argument("username", nargs="?")
|
|
args = parser.parse_args()
|
|
if args.action == "prepare":
|
|
prepare()
|
|
return
|
|
if args.action == "database":
|
|
provision_database()
|
|
return
|
|
bao = administrative_bao()
|
|
if args.action == "init":
|
|
initialize_bao(bao)
|
|
elif args.action == "unseal":
|
|
unseal(bao)
|
|
elif args.action == "seal":
|
|
bao.request("sys/seal", {}, operator_credentials()["root_token"], "PUT")
|
|
elif args.action == "configure":
|
|
configure_bao(bao)
|
|
elif args.action == "rotate-s3-add":
|
|
rotate_s3(bao, "add")
|
|
else:
|
|
rotate_s3(bao, "remove", args.username)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|