lab7: HTTPS+mTLS, OpenBao AppRole, Argon2id, rate limits, hardening
This commit is contained in:
@@ -0,0 +1,169 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Operator bootstrap for OpenBao (lab7).
|
||||
|
||||
Run AFTER `docker compose up -d openbao` and BEFORE starting the API:
|
||||
|
||||
python scripts/openbao_bootstrap.py
|
||||
|
||||
It initializes OpenBao (once), unseals it, creates the KV v2 path, writes the
|
||||
runtime credentials that are already in ./secrets, installs the scoped policy,
|
||||
enables AppRole and writes role_id/secret_id files for the application.
|
||||
|
||||
Operator-held material (unseal key, root token) is written to
|
||||
./secrets/openbao_init.json and never leaves this machine. The application
|
||||
never sees it. Delete ./secrets/openbao_init.json only after moving unseal
|
||||
material to a safe place.
|
||||
"""
|
||||
import base64
|
||||
import json
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
ENV = ["docker", "compose", "--env-file", ".env"]
|
||||
INIT_FILE = ROOT / "secrets" / "openbao_init.json"
|
||||
|
||||
|
||||
def read(name: str) -> str:
|
||||
return (ROOT / "secrets" / name).read_text().strip()
|
||||
|
||||
|
||||
def bao(*args: str, stdin: str | None = None, token: str | None = None):
|
||||
command = ENV + ["exec", "-T"]
|
||||
if token:
|
||||
command += ["-e", f"BAO_TOKEN={token}"]
|
||||
command += ["openbao", "bao", *args]
|
||||
return subprocess.run(command, cwd=ROOT, input=stdin, text=True, capture_output=True)
|
||||
|
||||
|
||||
def wait_for_container() -> None:
|
||||
for _ in range(60):
|
||||
probe = bao("status")
|
||||
if probe.returncode in (0, 2):
|
||||
return
|
||||
time.sleep(1)
|
||||
raise SystemExit("OpenBao container is not reachable: " + probe.stderr.strip())
|
||||
|
||||
|
||||
def status() -> dict:
|
||||
probe = bao("status", "-format=json")
|
||||
try:
|
||||
return json.loads(probe.stdout)
|
||||
except ValueError:
|
||||
return {"initialized": False, "sealed": True}
|
||||
|
||||
|
||||
def ensure_initialized() -> tuple[str, str]:
|
||||
current = status()
|
||||
if not current.get("initialized", False):
|
||||
if INIT_FILE.exists():
|
||||
raise SystemExit("OpenBao is uninitialized but secrets/openbao_init.json exists; "
|
||||
"refusing to overwrite operator material")
|
||||
init = bao("operator", "init", "-format=json", "-key-shares=1", "-key-threshold=1")
|
||||
if init.returncode != 0:
|
||||
raise SystemExit("operator init failed: " + init.stderr.strip())
|
||||
data = json.loads(init.stdout)
|
||||
INIT_FILE.write_text(json.dumps(data, indent=2))
|
||||
INIT_FILE.chmod(0o600)
|
||||
print("OpenBao initialized; unseal key and root token saved to secrets/openbao_init.json")
|
||||
data = json.loads(INIT_FILE.read_text())
|
||||
key = data["unseal_keys_b64"][0]
|
||||
token = data["root_token"]
|
||||
return key, token
|
||||
|
||||
|
||||
def ensure_unsealed(key: str) -> None:
|
||||
if status().get("sealed", True):
|
||||
unseal = bao("operator", "unseal", key)
|
||||
if unseal.returncode != 0:
|
||||
raise SystemExit("unseal failed: " + unseal.stderr.strip())
|
||||
print("OpenBao unsealed")
|
||||
|
||||
|
||||
def ensure_kv(token: str) -> None:
|
||||
mounts = bao("secrets", "list", "-format=json", token=token)
|
||||
existing = json.loads(mounts.stdout or "{}")
|
||||
if "kv/" not in existing:
|
||||
enable = bao("secrets", "enable", "-path=kv", "-version=2", "kv", token=token)
|
||||
if enable.returncode != 0:
|
||||
raise SystemExit("kv enable failed: " + enable.stderr.strip())
|
||||
print("Enabled kv v2 at kv/")
|
||||
|
||||
|
||||
def write_runtime_secrets(token: str) -> None:
|
||||
pg_password = read("postgres_password.txt")
|
||||
broker_user = read("broker_user.txt")
|
||||
broker_password = read("broker_password.txt")
|
||||
database_url = ("postgresql+psycopg://messenger:" + pg_password +
|
||||
"@postgres:5432/messenger?sslmode=verify-full&sslrootcert=/pki/ca.crt")
|
||||
broker_url = f"amqps://{broker_user}:{broker_password}@broker:5671/"
|
||||
write = bao("kv", "put", "kv/messenger",
|
||||
f"database_url={database_url}",
|
||||
f"s3_access_key_id={read('s3_access_key_id.txt')}",
|
||||
f"s3_secret_access_key={read('s3_secret_access_key.txt')}",
|
||||
f"broker_url={broker_url}",
|
||||
token=token)
|
||||
if write.returncode != 0:
|
||||
raise SystemExit("kv put failed: " + write.stderr.strip())
|
||||
print("Wrote kv/messenger")
|
||||
|
||||
|
||||
def install_policy(token: str) -> None:
|
||||
policy = (ROOT / "infra" / "openbao" / "policy-messenger.hcl").read_text()
|
||||
write = bao("policy", "write", "messenger", "-", stdin=policy, token=token)
|
||||
if write.returncode != 0:
|
||||
raise SystemExit("policy write failed: " + write.stderr.strip())
|
||||
print("Installed policy messenger")
|
||||
|
||||
|
||||
def ensure_approle(token: str) -> None:
|
||||
enable = bao("auth", "enable", "approle", token=token)
|
||||
if enable.returncode != 0 and "path is already in use" not in (enable.stderr or ""):
|
||||
if "already enabled" not in (enable.stderr or ""):
|
||||
raise SystemExit("approle enable failed: " + enable.stderr.strip())
|
||||
role = bao("write", "auth/approle/role/messenger",
|
||||
"token_ttl=1h", "token_max_ttl=4h", "secret_id_ttl=24h",
|
||||
"policies=messenger", token=token)
|
||||
if role.returncode != 0:
|
||||
raise SystemExit("approle role failed: " + role.stderr.strip())
|
||||
role_id = bao("read", "-field=role_id", "auth/approle/role/messenger/role-id", token=token)
|
||||
secret_id = bao("write", "-f", "-field=secret_id", "auth/approle/role/messenger/secret-id", token=token)
|
||||
if role_id.returncode != 0 or secret_id.returncode != 0:
|
||||
raise SystemExit("could not issue AppRole credentials")
|
||||
(ROOT / "secrets" / "openbao_role_id.txt").write_text(role_id.stdout.strip())
|
||||
(ROOT / "secrets" / "openbao_secret_id.txt").write_text(secret_id.stdout.strip())
|
||||
print("Issued AppRole role_id/secret_id")
|
||||
|
||||
|
||||
def self_check(role_id: str, secret_id: str) -> None:
|
||||
login = bao("write", "-format=json", "auth/approle/login",
|
||||
f"role_id={role_id}", f"secret_id={secret_id}")
|
||||
if login.returncode != 0:
|
||||
raise SystemExit("AppRole login self-check failed: " + login.stderr.strip())
|
||||
token = json.loads(login.stdout)["auth"]["client_token"]
|
||||
read_back = bao("kv", "get", "-format=json", "kv/messenger", token=token)
|
||||
if read_back.returncode != 0:
|
||||
raise SystemExit("policy cannot read kv/messenger: " + read_back.stderr.strip())
|
||||
forbidden = bao("kv", "get", "-format=json", "kv/other", token=token)
|
||||
if forbidden.returncode == 0:
|
||||
raise SystemExit("policy unexpectedly reads kv/other")
|
||||
print("AppRole login and scoped policy verified (kv/other denied)")
|
||||
|
||||
|
||||
def main() -> None:
|
||||
wait_for_container()
|
||||
key, root = ensure_initialized()
|
||||
ensure_unsealed(key)
|
||||
ensure_kv(root)
|
||||
write_runtime_secrets(root)
|
||||
install_policy(root)
|
||||
ensure_approle(root)
|
||||
self_check((ROOT / "secrets" / "openbao_role_id.txt").read_text().strip(),
|
||||
(ROOT / "secrets" / "openbao_secret_id.txt").read_text().strip())
|
||||
print("OpenBao bootstrap complete. Start the rest: docker compose up -d")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in New Issue
Block a user