132 lines
5.3 KiB
Python
132 lines
5.3 KiB
Python
"""Initialize, unseal and provision the local OpenBao without printing credentials."""
|
|
|
|
import argparse
|
|
import json
|
|
import os
|
|
import ssl
|
|
import subprocess
|
|
import time
|
|
from pathlib import Path
|
|
from urllib.error import HTTPError, URLError
|
|
from urllib.parse import urlsplit
|
|
from urllib.request import Request, urlopen
|
|
|
|
ROOT = Path(__file__).resolve().parents[1]
|
|
|
|
|
|
def from_bootstrap(filename):
|
|
result = subprocess.run(
|
|
["docker", "compose", "run", "--rm", "--no-deps", "--entrypoint", "cat", "bootstrap",
|
|
f"/state/operator/{filename}"],
|
|
cwd=ROOT, check=True, capture_output=True,
|
|
)
|
|
return result.stdout
|
|
|
|
|
|
def request(address, context, path, body=None, token=None):
|
|
content = json.dumps(body).encode() if body is not None else None
|
|
headers = {"Content-Type": "application/json"}
|
|
if token:
|
|
headers["X-Vault-Token"] = token
|
|
req = Request(address + "/v1/" + path, data=content, headers=headers)
|
|
try:
|
|
with urlopen(req, context=context, timeout=5) as response:
|
|
return json.loads(response.read() or "{}")
|
|
except HTTPError as error:
|
|
raise RuntimeError(f"OpenBao {path}: HTTP {error.code}") from None
|
|
|
|
|
|
def wait_for_listener(address, context):
|
|
for _ in range(30):
|
|
try:
|
|
return request(address, context, "sys/init")["initialized"]
|
|
except ssl.SSLCertVerificationError:
|
|
raise
|
|
except URLError as error:
|
|
if isinstance(error.reason, ssl.SSLCertVerificationError):
|
|
raise
|
|
time.sleep(1)
|
|
raise RuntimeError("OpenBao listener did not become available")
|
|
|
|
|
|
def save_operator_file(path, state):
|
|
path.parent.mkdir(parents=True, exist_ok=True, mode=0o700)
|
|
with os.fdopen(os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600), "w",
|
|
encoding="utf-8") as file:
|
|
json.dump(state, file)
|
|
file.flush()
|
|
os.fsync(file.fileno())
|
|
|
|
|
|
def configure(address, context, token):
|
|
mounts = request(address, context, "sys/mounts", token=token)
|
|
if "messenger/" not in mounts:
|
|
request(address, context, "sys/mounts/messenger",
|
|
{"type": "kv", "options": {"version": "2"}}, token)
|
|
auth = request(address, context, "sys/auth", token=token)
|
|
if "cert/" not in auth:
|
|
request(address, context, "sys/auth/cert", {"type": "cert"}, token)
|
|
|
|
roles = json.loads(from_bootstrap("roles.json"))
|
|
template = (ROOT / "infra/openbao/service.hcl").read_text(encoding="utf-8")
|
|
for role, config in roles.items():
|
|
policy = "messenger-" + role
|
|
request(address, context, "sys/policies/acl/" + policy,
|
|
{"policy": template.replace("ROLE", role)}, token)
|
|
request(address, context, "auth/cert/certs/" + role, {
|
|
"certificate": config["certificate"],
|
|
"allowed_dns_sans": [role + ".bao.lab7.internal"],
|
|
"token_policies": [policy],
|
|
"token_ttl": "15m",
|
|
"token_explicit_max_ttl": "15m",
|
|
"token_no_default_policy": True,
|
|
}, token)
|
|
request(address, context, "messenger/data/" + role, {"data": config["values"]}, token)
|
|
|
|
|
|
def main():
|
|
parser = argparse.ArgumentParser(description=__doc__)
|
|
parser.add_argument("action", choices=("init", "unseal"))
|
|
parser.add_argument("--address", default="https://localhost:8200")
|
|
parser.add_argument("--operator-file", type=Path,
|
|
default=Path(os.environ.get("LAB7_OPERATOR_FILE", ROOT / "secrets/operator.json")))
|
|
parser.add_argument("--ca-file", type=Path, default=ROOT / "secrets/ca.crt")
|
|
args = parser.parse_args()
|
|
address = args.address.rstrip("/")
|
|
parsed = urlsplit(address)
|
|
if parsed.scheme != "https" or parsed.hostname not in ("localhost", "127.0.0.1") or parsed.path:
|
|
parser.error("--address must be a local HTTPS origin")
|
|
|
|
if args.action == "init":
|
|
args.ca_file.parent.mkdir(parents=True, exist_ok=True, mode=0o700)
|
|
args.ca_file.write_bytes(from_bootstrap("ca.crt"))
|
|
context = ssl.create_default_context(cafile=str(args.ca_file))
|
|
initialized = wait_for_listener(address, context)
|
|
if not initialized:
|
|
if args.action != "init" or args.operator_file.exists():
|
|
raise RuntimeError("Use init with a new operator file to initialize this storage")
|
|
state = request(address, context, "sys/init", {"secret_shares": 3, "secret_threshold": 2})
|
|
save_operator_file(args.operator_file, state)
|
|
else:
|
|
state = json.loads(args.operator_file.read_text(encoding="utf-8"))
|
|
for share in state["keys_base64"][:2]:
|
|
if not request(address, context, "sys/seal-status")["sealed"]:
|
|
break
|
|
request(address, context, "sys/unseal", {"key": share})
|
|
if request(address, context, "sys/seal-status")["sealed"]:
|
|
raise RuntimeError("OpenBao is still sealed")
|
|
if args.action == "init":
|
|
configure(address, context, state["root_token"])
|
|
print("OpenBao is unsealed. Service policies and KV paths are provisioned.")
|
|
else:
|
|
print("OpenBao is unsealed.")
|
|
|
|
|
|
if __name__ == "__main__":
|
|
try:
|
|
main()
|
|
except subprocess.CalledProcessError:
|
|
raise SystemExit("Could not read bootstrap material from Docker Compose.") from None
|
|
except (OSError, RuntimeError) as error:
|
|
raise SystemExit(str(error)) from None
|